hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
3363005bdf8208cc0286b9b2a78871a8ad6baead | 1,186 | package com.thebluealliance.androidclient.subscribers;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.thebluealliance.androidclient.listitems.ContributorListElement;
import com.thebluealliance.androidclient.listitems.ListItem;
import java.util.ArrayList;
import java.util.List;
public class ContributorListSubscriber extends BaseAPISubscriber<JsonElement, List<ListItem>> {
public ContributorListSubscriber() {
mDataToBind = new ArrayList<>();
}
@Override
public void parseData() {
mDataToBind.clear();
JsonArray data = mAPIData.getAsJsonArray();
for (JsonElement e : data) {
JsonObject user = e.getAsJsonObject();
String username = user.get("login").getAsString();
int contributionCount = user.get("contributions").getAsInt();
String avatarUrl = user.get("avatar_url").getAsString();
mDataToBind.add(new ContributorListElement(username, contributionCount, avatarUrl));
}
}
@Override public boolean isDataValid() {
return super.isDataValid() && mAPIData.isJsonArray();
}
}
| 32.944444 | 96 | 0.705734 |
bf4a86360a41b5f86f1e4f813d22f392a7fa5053 | 4,390 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.service.launcher;
import java.lang.Thread.UncaughtExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.classification.InterfaceAudience.Public;
import org.apache.hadoop.classification.InterfaceStability.Evolving;
import org.apache.hadoop.util.ExitUtil;
import org.apache.hadoop.util.ShutdownHookManager;
/**
* This class is intended to be installed by calling
* {@link Thread#setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler)}
* in the main entry point.
*
* The base class will always attempt to shut down the process if an Error
* was raised; the behavior on a standard Exception, raised outside
* process shutdown, is simply to log it.
*
* (Based on the class {@code YarnUncaughtExceptionHandler})
*/
@SuppressWarnings("UseOfSystemOutOrSystemErr")
@Public
@Evolving
public class HadoopUncaughtExceptionHandler
implements UncaughtExceptionHandler {
/**
* Logger.
*/
private static final Logger LOG = LoggerFactory.getLogger(
HadoopUncaughtExceptionHandler.class);
/**
* Delegate for simple exceptions.
*/
private final UncaughtExceptionHandler delegate;
/**
* Create an instance delegating to the supplied handler if
* the exception is considered "simple".
* @param delegate a delegate exception handler.
*/
public HadoopUncaughtExceptionHandler(UncaughtExceptionHandler delegate) {
this.delegate = delegate;
}
/**
* Basic exception handler -logs simple exceptions, then continues.
*/
public HadoopUncaughtExceptionHandler() {
this(null);
}
/**
* Uncaught exception handler.
* If an error is raised: shutdown
* The state of the system is unknown at this point -attempting
* a clean shutdown is dangerous. Instead: exit
* @param thread thread that failed
* @param exception the raised exception
*/
@Override
public void uncaughtException(Thread thread, Throwable exception) {
if (ShutdownHookManager.get().isShutdownInProgress()) {
LOG.error("Thread {} threw an error during shutdown: {}.",
thread.toString(),
exception,
exception);
} else if (exception instanceof Error) {
try {
LOG.error("Thread {} threw an error: {}. Shutting down",
thread.toString(),
exception,
exception);
} catch (Throwable err) {
// We don't want to not exit because of an issue with logging
}
if (exception instanceof OutOfMemoryError) {
// After catching an OOM java says it is undefined behavior, so don't
// even try to clean up or we can get stuck on shutdown.
try {
System.err.println("Halting due to Out Of Memory Error...");
} catch (Throwable err) {
// Again we don't want to exit because of logging issues.
}
ExitUtil.haltOnOutOfMemory((OutOfMemoryError) exception);
} else {
// error other than OutOfMemory
ExitUtil.ExitException ee =
ServiceLauncher.convertToExitException(exception);
ExitUtil.terminate(ee.status, ee);
}
} else {
// simple exception in a thread. There's a policy decision here:
// terminate the process vs. keep going after a thread has failed
// base implementation: do nothing but log
LOG.error("Thread {} threw an exception: {}",
thread.toString(),
exception,
exception);
if (delegate != null) {
delegate.uncaughtException(thread, exception);
}
}
}
}
| 33.769231 | 78 | 0.69385 |
429bf627e8c22a85eeedbd73958d2c41e008b8c4 | 3,439 | //<start id="ne-setup"/>
protected void doPost(HttpServletRequest request,
HttpServletResponse response, Session session)
throws ServletException, IOException, TheBlendException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
throw new TheBlendException("Invalid request!");
}
// --- get the content for the next version ---
File uploadedFile = null;
String mimeType = null;
String docPath = null;
ObjectId newVersionId = null;
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(50 * 1024 * 1024);
@SuppressWarnings("unchecked")
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
String name = item.getFieldName();
if ("path".equalsIgnoreCase(name)) {
docPath = item.getString();
}
}
else {
uploadedFile = File.createTempFile("blend", "tmp");
item.write(uploadedFile);
mimeType = item.getContentType();
if (mimeType == null) {
mimeType = "application/octet-stream";
}
}
}
} catch (Exception e) {
throw new TheBlendException("Upload failed: " + e, e);
}
if (uploadedFile == null) {
throw new TheBlendException("No content!");
}
FileInputStream stream = null;
try {
// --- fetch the document ---
CmisObject cmisObject = null;
try {
cmisObject = session.getObjectByPath(docPath);
} catch (CmisBaseException cbe) {
throw new TheBlendException(
"Could not retrieve the document!", cbe);
}
Document doc = null;
if (cmisObject instanceof Document) {
doc = (Document) cmisObject;
} else {
throw new TheBlendException("Object is not a document!");
}
// --- prepare the content ---
stream = new FileInputStream(uploadedFile);
ContentStream contentStream =
session.getObjectFactory().createContentStream(
doc.getContentStreamFileName(), uploadedFile.length(),
mimeType, stream);
// --- do the check out ---
Document pwc = null;
try {
ObjectId pwcId = doc.checkOut();
pwc = (Document) session.getObject(pwcId);
} catch (CmisBaseException cbe) {
throw new TheBlendException(
"Could not check out the document!", cbe);
}
// --- do the check in ---
try {
newVersionId = pwc.checkIn(true, null, contentStream, null); //<co id="ch8_checkin_1" />
} catch (CmisBaseException cbe) {
throw new TheBlendException(
"Could not check in the document!", cbe); //<co id="ch8_checkin_2" />
}
}
finally {
if (stream != null) {
try {
stream.close();
}
catch (IOException ioe) {
// ignore
}
}
uploadedFile.delete();
}
// --- redirect to show page ---
try {
String url = request.getRequestURL().toString();
int lastSlash = url.lastIndexOf('/');
url = url.substring(0, lastSlash) + "/show?id=" +
URLEncoder.encode(newVersionId.getId(), "UTF-8");
redirect(url, request, response);
}
catch(UnsupportedEncodingException e) {
throw new ServletException(e);
}
}
//<end id="ne-setup"/>
| 27.07874 | 94 | 0.614423 |
8d51bb58fc76c78b44a6a11d4fe58acaef85b5cb | 683 | package com.facebook.react.fabric.mounting.mountitems;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.fabric.mounting.MountingManager;
public class UpdatePropsMountItem implements MountItem {
private final int mReactTag;
private final ReadableMap mUpdatedProps;
public UpdatePropsMountItem(int i, ReadableMap readableMap) {
this.mReactTag = i;
this.mUpdatedProps = readableMap;
}
public void execute(MountingManager mountingManager) {
mountingManager.updateProps(this.mReactTag, this.mUpdatedProps);
}
public String toString() {
return "UpdatePropsMountItem [" + this.mReactTag + "]";
}
}
| 29.695652 | 72 | 0.736457 |
7a5a40ce876c904a87d4526725b9dff7980f6fbb | 5,151 | package ca.uhn.fhir.jpa.binary.svc;
/*-
* #%L
* HAPI FHIR Storage api
* %%
* Copyright (C) 2014 - 2022 Smile CDR, 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.
* #L%
*/
import ca.uhn.fhir.i18n.Msg;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.jpa.binary.api.IBinaryStorageSvc;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.PayloadTooLargeException;
import ca.uhn.fhir.util.BinaryUtil;
import ca.uhn.fhir.util.HapiExtensions;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.hash.HashingInputStream;
import com.google.common.io.ByteStreams;
import org.apache.commons.io.input.CountingInputStream;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.instance.model.api.IBaseBinary;
import org.hl7.fhir.instance.model.api.IBaseHasExtensions;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.instance.model.api.IPrimitiveType;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.Optional;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
public abstract class BaseBinaryStorageSvcImpl implements IBinaryStorageSvc {
private final SecureRandom myRandom;
private final String CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private final int ID_LENGTH = 100;
private int myMaximumBinarySize = Integer.MAX_VALUE;
private int myMinimumBinarySize;
@Autowired
private FhirContext myFhirContext;
public BaseBinaryStorageSvcImpl() {
myRandom = new SecureRandom();
}
@Override
public int getMaximumBinarySize() {
return myMaximumBinarySize;
}
@Override
public void setMaximumBinarySize(int theMaximumBinarySize) {
Validate.inclusiveBetween(1, Integer.MAX_VALUE, theMaximumBinarySize);
myMaximumBinarySize = theMaximumBinarySize;
}
@Override
public int getMinimumBinarySize() {
return myMinimumBinarySize;
}
@Override
public void setMinimumBinarySize(int theMinimumBinarySize) {
myMinimumBinarySize = theMinimumBinarySize;
}
@Override
public String newBlobId() {
StringBuilder b = new StringBuilder();
for (int i = 0; i < ID_LENGTH; i++) {
int nextInt = Math.abs(myRandom.nextInt());
b.append(CHARS.charAt(nextInt % CHARS.length()));
}
return b.toString();
}
@Override
public boolean shouldStoreBlob(long theSize, IIdType theResourceId, String theContentType) {
return theSize >= getMinimumBinarySize();
}
@SuppressWarnings("UnstableApiUsage")
@Nonnull
protected HashingInputStream createHashingInputStream(InputStream theInputStream) {
HashFunction hash = Hashing.sha256();
return new HashingInputStream(hash, theInputStream);
}
@Nonnull
protected CountingInputStream createCountingInputStream(InputStream theInputStream) {
InputStream is = ByteStreams.limit(theInputStream, getMaximumBinarySize() + 1L);
return new CountingInputStream(is) {
@Override
public int getCount() {
int retVal = super.getCount();
if (retVal > getMaximumBinarySize()) {
throw new PayloadTooLargeException(Msg.code(1343) + "Binary size exceeds maximum: " + getMaximumBinarySize());
}
return retVal;
}
};
}
protected String provideIdForNewBlob(String theBlobIdOrNull) {
String id = theBlobIdOrNull;
if (isBlank(theBlobIdOrNull)) {
id = newBlobId();
}
return id;
}
@Override
public byte[] fetchDataBlobFromBinary(IBaseBinary theBaseBinary) throws IOException {
IPrimitiveType<byte[]> dataElement = BinaryUtil.getOrCreateData(myFhirContext, theBaseBinary);
byte[] value = dataElement.getValue();
if (value == null) {
Optional<String> attachmentId = getAttachmentId((IBaseHasExtensions) dataElement);
if (attachmentId.isPresent()) {
value = fetchBlob(theBaseBinary.getIdElement(), attachmentId.get());
} else {
throw new InternalErrorException(Msg.code(1344) + "Unable to load binary blob data for " + theBaseBinary.getIdElement());
}
}
return value;
}
@SuppressWarnings("unchecked")
private Optional<String> getAttachmentId(IBaseHasExtensions theBaseBinary) {
return theBaseBinary
.getExtension()
.stream()
.filter(t -> HapiExtensions.EXT_EXTERNALIZED_BINARY_ID.equals(t.getUrl()))
.filter(t -> t.getValue() instanceof IPrimitiveType)
.map(t -> (IPrimitiveType<String>) t.getValue())
.map(t -> t.getValue())
.filter(t -> isNotBlank(t))
.findFirst();
}
}
| 32.396226 | 125 | 0.763735 |
6ef44dd784fff0cd8a1d6e0632b9d62b2a1f1195 | 151 | package org.xpdojo.designpatterns._03_behavioral_patterns._07_observer.chat;
public interface Subscriber {
void handleMessage(String message);
}
| 21.571429 | 76 | 0.821192 |
e9b3c66ce9320db1f38155b3a493a870e6de5312 | 2,434 | /**
* Superklassen Hus som er byggesteinen til subklassene Bolig og Leilighet.
*
* @author Mathias N Evensen
* @version 1.3
*/
public class Hus
{
private int gateNummer;
private String gateNavn;
private int pris;
private String type; //what type of house it is ex. Condo, Apartment, House etc
private int kvadratMeter;
/**
* Constructor for objects of class Hus
* @param gateNummer gatenummer
* @param gateNavn gatenavnet
* @param pris prisen
* @param kvadratMeter antall kvadrat
*/
public Hus(int gateNummer, String gateNavn, int pris, int kvadratMeter)
{
this.gateNummer = gateNummer;
this.gateNavn = gateNavn;
this.pris = pris;
this.kvadratMeter = kvadratMeter;
}
/**
* Constructor for objects of class Hus
* @param gateNummer gatenummer
* @param gateNavn gatenavnet
* @param pris prisen
* @param type hvilket type hus
* @param kvadratMeter antall kvadrat
*/
public Hus(int gateNummer, String gateNavn, int pris, String type, int kvadratMeter)
{
this.gateNummer = gateNummer;
this.gateNavn = gateNavn;
this.pris = pris;
this.type = type;
this.kvadratMeter = kvadratMeter;
}
/**
* @return gateNummer
*/
public int getGateNummer()
{
return gateNummer;
}
/**
* @return gateNavn
*/
public String getGateNavn()
{
return gateNavn;
}
/**
* @return pris
*/
public int getPris()
{
return pris;
}
/**
* @return type
*/
public String getType()
{
return type;
}
/**
* @param type hus
*/
public void setType(String type)
{
this.type = type;
}
/**
* @return kvadratMeter
*/
public int getKvadratMeter()
{
return kvadratMeter;
}
/**
* Printer ut all informasjonen om et hus
*/
public void printInformasjon()
{
System.out.println("____________________________");
System.out.println("Adressen er: " + gateNavn + " " + gateNummer);
System.out.println("Pris: " + pris + " Kroner");
System.out.println("Type hus: " + type);
System.out.println("Kvadratmeter: " + kvadratMeter + "m" + "\u00B2");
System.out.println();
}
}
| 22.330275 | 88 | 0.565325 |
867edb38e8594a7ca73a82a253d9b30506234c6a | 3,689 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package ai.deepcode.jbplugin.ui.nodes;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.projectView.impl.ProjectRootsUtil;
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode;
import ai.deepcode.jbplugin.ui.TodoTreeBuilder;
import ai.deepcode.jbplugin.ui.TodoTreeStructure;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.file.SourceRootIconProvider;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.Iterator;
public final class TodoDirNode extends PsiDirectoryNode {
private final TodoTreeBuilder myBuilder;
public TodoDirNode(Project project,
@NotNull PsiDirectory directory,
TodoTreeBuilder builder) {
super(project, directory, ViewSettings.DEFAULT);
myBuilder = builder;
}
@Override
protected void updateImpl(@NotNull PresentationData data) {
super.updateImpl(data);
int fileCount = getFileCount(getValue());
if (getValue() == null || !getValue().isValid() || fileCount == 0) {
setValue(null);
return;
}
VirtualFile directory = getValue().getVirtualFile();
boolean isProjectRoot = !ProjectRootManager.getInstance(getProject()).getFileIndex().isInContent(directory);
String newName = isProjectRoot || getStructure().getIsFlattenPackages() ? getValue().getVirtualFile().getPresentableUrl() : getValue().getName();
int todoItemCount = getTodoItemCount(getValue());
data.setLocationString(IdeBundle.message("node.todo.group", todoItemCount));
data.setPresentableText(newName);
}
@Override
protected void setupIcon(PresentationData data, PsiDirectory psiDirectory) {
final VirtualFile virtualFile = psiDirectory.getVirtualFile();
if (ProjectRootsUtil.isModuleContentRoot(virtualFile, psiDirectory.getProject())) {
data.setIcon(new SourceRootIconProvider.DirectoryProvider().getIcon(psiDirectory, 0));
} else {
super.setupIcon(data, psiDirectory);
}
}
private TodoTreeStructure getStructure() {
return myBuilder.getTodoTreeStructure();
}
@Override
public Collection<AbstractTreeNode> getChildrenImpl() {
return TodoTreeHelper.getInstance(getProject()).getDirectoryChildren(getValue(), myBuilder, getSettings().isFlattenPackages());
}
public int getFileCount(PsiDirectory directory) {
Iterator<PsiFile> iterator = myBuilder.getFiles(directory);
int count = 0;
try {
while (iterator.hasNext()) {
PsiFile psiFile = iterator.next();
if (getStructure().accept(psiFile)) {
count++;
}
}
}
catch (IndexNotReadyException e) {
return count;
}
return count;
}
public int getTodoItemCount(PsiDirectory directory) {
if (TodoTreeHelper.getInstance(getProject()).skipDirectory(directory)) {
return 0;
}
int count = 0;
Iterator<PsiFile> iterator = myBuilder.getFiles(directory);
while (iterator.hasNext()) {
PsiFile psiFile = iterator.next();
count += getStructure().getTodoItemCount(psiFile);
}
return count;
}
@Override
public int getWeight() {
return 2;
}
}
| 33.536364 | 149 | 0.731364 |
7adf6e8bcc80e9ee2f0b4e471009c1ec4d77a43a | 289 | package com.grizzly.rest.Model;
/**
* Implement this interface in the summoner class to perform any fallback operations when the rest call fails.
* Created by Fco Pardo on 8/24/14.
*/
public interface afterTaskFailure<T> {
<L extends Exception> void onTaskFailed(T result, L e);
}
| 28.9 | 110 | 0.740484 |
dd54359f51ebf50dde41824bb3adb4dfb840ba77 | 264 | package com.ja.smarkdown.model.config;
import com.ja.smarkdown.json.AbstractParser;
public class SmarkdownConfigurationParser extends
AbstractParser<SmarkdownConfiguration> {
public SmarkdownConfigurationParser() {
super(SmarkdownConfiguration.class);
}
} | 24 | 49 | 0.825758 |
be00d4238dd428583139c4c680316f2aec44282c | 1,428 | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.tools.dataextractor.report.views;
import java.util.List;
/*****
* Region view based on persistent view
* Its made of List<RegionViewInfoPerGroup>
* @author bansods
*
*/
public class RegionView {
List<RegionViewInfoPerGroup> regionViewInfoPerGroupList;
boolean viewConflict = false;
public boolean isViewConflicted() {
return viewConflict;
}
public RegionView (List<RegionViewInfoPerGroup> regionViewInfoPerGroupList){
this.regionViewInfoPerGroupList = regionViewInfoPerGroupList;
if (regionViewInfoPerGroupList.size() > 1) {
viewConflict = true;
}
}
public List<RegionViewInfoPerGroup> getRegionViewInfoPerGroupList() {
return regionViewInfoPerGroupList;
}
}
| 29.142857 | 78 | 0.745798 |
7b4a1540837e22063f23ee50745f4674301f09b4 | 346 | package edu.bu.met.cs665.dataProcessingCommand;
import java.util.ArrayList;
import java.util.List;
public class DataProcessor {
/** a list of command to store history of commands*/
private List<Command> history = new ArrayList<>();
public void storeAndExecute(final Command cmd){
this.history.add(cmd);
cmd.execute();
}
}
| 21.625 | 54 | 0.716763 |
81d3076084a9fb6e322e1cf2c850eca13b1a7d43 | 1,393 | package com.galaxy.galaxyquests.storage.adapters;
import com.google.gson.*;
import com.galaxy.galaxyquests.objects.user.TimedQuestData;
import me.hyfe.simplespigot.storage.adapter.Adapter;
import java.lang.reflect.Type;
import java.time.ZonedDateTime;
public class TimedQuestDataAdapter implements Adapter<TimedQuestData> {
@Override
public TimedQuestData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String timeStartedString = jsonObject.get("timeStarted").getAsString();
ZonedDateTime timeStarted = timeStartedString.equals("none") ? null : ZonedDateTime.parse(timeStartedString);
int completions = jsonObject.get("completions").getAsInt();
int attempts = jsonObject.get("attempts").getAsInt();
return new TimedQuestData(timeStarted, completions, attempts);
}
@Override
public JsonElement serialize(TimedQuestData src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("timeStarted", src.getTimeStarted() == null ? "none" : src.getTimeStarted().toString());
jsonObject.addProperty("completions", src.getCompletions());
jsonObject.addProperty("attempts", src.getAttempts());
return jsonObject;
}
} | 46.433333 | 133 | 0.74659 |
02272abf71985d170e0d71d515047d4e302fa84f | 1,331 | package neal.java.zk;
import org.apache.zookeeper.*;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class ZKCreateGroup implements Watcher {
private static final int SESSION_TIMEOUT = 5000;
private ZooKeeper zk;
private CountDownLatch connectedSignal = new CountDownLatch(1);
public void connect(String hosts) throws IOException, InterruptedException {
zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);
connectedSignal.await();
}
@Override
public void process(WatchedEvent event) { // Watcher interface
if (event.getState() == Event.KeeperState.SyncConnected) {
connectedSignal.countDown();
}
}
public void create(String groupName) throws KeeperException, InterruptedException {
String path = "/" + groupName;
String createdPath = zk.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
System.out.println("Created " + createdPath);
}
public void close() throws InterruptedException {
zk.close();
}
public static void main(String[] args) throws Exception {
ZKCreateGroup createGroup = new ZKCreateGroup();
createGroup.connect("localhost");
createGroup.create("zk");
createGroup.close();
}
}
| 30.25 | 87 | 0.677686 |
b61c4f446f71690b3cb25af30debe3b1d186cd96 | 4,110 | package com.zzw.wexinsample.ui.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
/**
* 字母索引栏
* Created by zouzhiwei on 2015/8/28.
*/
public class LetterBar extends View {
//用于Log的tag
private final String TAG = getClass().getSimpleName();
//26个英文字母数组
private String[] letters;
//用于在canvas画出字母
private Paint paint;
//点击的字母的下标
private int chooseIndex = -1;
//字母改变回调接口
private OnLetterChangeListener onLetterChangeListener;
//用于在界面显示点击的字母
private TextView tvTip;
public LetterBar(Context context) {
this(context, null);
}
public LetterBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LetterBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//初始化
init();
}
/**
* 初始化
*/
private void init() {
//初始化画笔
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
paint.setTextSize(28);
//初始化字母数组
letters = new String[]{"↑", "☆", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#"};
}
/**
* 设置提示字母的TextView
*
* @param tvTip
*/
public void setTvTip(TextView tvTip) {
this.tvTip = tvTip;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//获取布局的宽和高
int width = getWidth();
int height = getHeight();
//计算每个字母的高度
int letterHeight = height / letters.length;
//画出每个字母
for (int i = 0; i < letters.length; i++) {
//计算每个字母的坐标
float xPos = (width - paint.measureText(letters[i])) / 2;
float yPos = letterHeight * i + letterHeight;
//在画布上画出字母
canvas.drawText(letters[i], xPos, yPos, paint);
}
}
/**
* 还原字母侧边栏
*/
public void reSet() {
setBackgroundDrawable(new ColorDrawable(0x0000));
if (tvTip != null) {
tvTip.setVisibility(View.GONE);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
int oldChooseIndex = chooseIndex;
chooseIndex = (int) ((event.getY() / getHeight()) * letters.length);
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
setBackgroundDrawable(new ColorDrawable(0x0000));
if (tvTip != null) {
tvTip.setVisibility(View.GONE);
}
break;
default:
setBackgroundColor(Color.GRAY);
if (oldChooseIndex != chooseIndex) {
if (chooseIndex >= 0 && chooseIndex < letters.length) {
Log.i(TAG, "letter:" + letters[chooseIndex]);
if (onLetterChangeListener != null) {
//当设置了回调接口后,返回点击的字母
onLetterChangeListener.onLetterChange(letters[chooseIndex]);
}
if (tvTip != null) {
tvTip.setVisibility(View.VISIBLE);
tvTip.setText(letters[chooseIndex]);
}
invalidate();
}
}
break;
}
return true;
}
/**
* 设置回调接口
*
* @param onLetterChangeListener
*/
public void setOnLetterChangeListener(OnLetterChangeListener onLetterChangeListener) {
this.onLetterChangeListener = onLetterChangeListener;
}
/**
* 字母回调接口
*/
public interface OnLetterChangeListener {
public void onLetterChange(String s);
}
}
| 28.344828 | 115 | 0.542579 |
16cde3f6cddac5a302e87dfc59fe0987d656ce38 | 1,026 | package io.tacsio.envdocker;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@SpringBootApplication
public class EnvdockerApplication {
public static void main(String[] args) {
SpringApplication.run(EnvdockerApplication.class, args);
}
}
@RestController
class EnvController {
@Value("${FROM_START}")
String fromStart;
@Value("${FROM_DOCKERFILE}")
String fromDocker;
@Value("${FROM_KUBERNETES}")
String fromKubernetes;
@GetMapping
public ResponseEntity envs() {
Map<String, String> envs = new HashMap<>();
envs.put("start", fromStart);
envs.put("docker", fromDocker);
envs.put("kubernetes", fromKubernetes);
return ResponseEntity.ok(envs);
}
}
| 23.318182 | 68 | 0.780702 |
d84b413c5138a40b8ff5e251ca4838db3d732132 | 2,275 | package org.woo.context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
public class ApiRequestContext implements AutoCloseable {
private HttpServletRequest request;
private HttpServletResponse response;
private BindInData bindInData;
private BindOutData bindOutData;
@Override
public void close() throws Exception {
}
private static final Logger LOGGER = LoggerFactory.getLogger(ApiRequestContext.class);
private static final ApiRequestContext INSTANCE = new ApiRequestContext();
public final static ApiRequestContext get() {
return INSTANCE;
}
private ApiRequestContext() {
super();
}
public HttpServletResponse getResponse() {
return response;
}
public Map<String, String> getParameterMap() {
Map<String, String> result = new HashMap<>();
Map<String, String[]> map = this.request.getParameterMap();
for (String key : map.keySet()) {
String[] values = map.get(key);
String value = values == null ? null : values[0];
result.put(key, value);
}
LOGGER.debug(result.toString());
return result;
}
public String getParameterValue(String param) {
bindOutData.close();
return this.request.getParameter(param);
}
public String getPostData() {
return null;
}
public <T> T getPostData(Class<T> tClass) {
return this.bindInData.getBody(tClass);
}
public String getHeaderValue(String header) {
return this.request.getHeader(header);
}
public HttpServletRequest getRequest() {
return request;
}
public HttpSession getSession() {
return getSession(true);
}
public HttpSession getSession(boolean create) {
return getRequest().getSession(create);
}
public String getSessionId() {
return getSession().getId();
}
public ServletContext getServletContext() {
return getSession().getServletContext(); // servlet2.3
}
} | 25.277778 | 90 | 0.665934 |
61c9ed9a61b079edbcfea8fa9bbf151b6cf1517e | 886 | package com.myc0058.paypush.Response;
import java.util.HashMap;
import java.util.Map;
/**
* A param for checking a IOS Receipt.
*
* @author YoungChul Mo
* @since 2016-04-24
*/
public class IOSPushsResponse {
private Integer successCount;
private Integer failCount;
//IOSPushsParam에서 isMoreDetail 변수가 true이면 채워주는 변수
//Map<DeviceToken, StatusCode>
private Map<String, Integer> failData = new HashMap<String, Integer>();
public Integer getSuccessCount() {
return successCount;
}
public void setSuccessCount(Integer successCount) {
this.successCount = successCount;
}
public Integer getFailCount() {
return failCount;
}
public void setFailCount(Integer failCount) {
this.failCount = failCount;
}
public Map<String, Integer> getFailData() {
return failData;
}
public void setFailData(Map<String, Integer> failData) {
this.failData = failData;
}
}
| 22.15 | 72 | 0.738149 |
b9c2a5e3b4bb927d22fd0ca4e7641471b1db50aa | 4,269 | package unit.com.bitdubai.fermat_cbp_plugin.layer.network_service.transaction_transmission.developer.bitdubai.version_1.structure.TransactionTransmissionAgent;
import com.bitdubai.fermat_api.layer.all_definition.common.system.annotations.NeededAddonReference;
import com.bitdubai.fermat_api.layer.all_definition.common.system.annotations.NeededPluginReference;
import com.bitdubai.fermat_api.layer.all_definition.components.interfaces.PlatformComponentProfile;
import com.bitdubai.fermat_api.layer.all_definition.crypto.asymmetric.ECCKeyPair;
import com.bitdubai.fermat_api.layer.all_definition.enums.Addons;
import com.bitdubai.fermat_api.layer.all_definition.enums.Layers;
import com.bitdubai.fermat_api.layer.all_definition.enums.Platforms;
import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins;
import com.bitdubai.fermat_cbp_plugin.layer.network_service.transaction_transmission.developer.bitdubai.version_1.TransactionTransmissionPluginRoot;
import com.bitdubai.fermat_cbp_plugin.layer.network_service.transaction_transmission.developer.bitdubai.version_1.database.TransactionTransmissionConnectionsDAO;
import com.bitdubai.fermat_cbp_plugin.layer.network_service.transaction_transmission.developer.bitdubai.version_1.database.TransactionTransmissionContractHashDao;
import com.bitdubai.fermat_cbp_plugin.layer.network_service.transaction_transmission.developer.bitdubai.version_1.structure.CommunicationNetworkServiceConnectionManager;
import com.bitdubai.fermat_cbp_plugin.layer.network_service.transaction_transmission.developer.bitdubai.version_1.structure.TransactionTransmissionAgent;
import com.bitdubai.fermat_p2p_api.layer.p2p_communication.WsCommunicationsCloudClientManager;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.interfaces.ErrorManager;
import com.bitdubai.fermat_pip_api.layer.platform_service.event_manager.interfaces.EventManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
/**
* Created by Gabriel Araujo ([email protected]) on 21/12/15.
*/
@RunWith(MockitoJUnitRunner.class)
public class StartTest {
@NeededAddonReference(platform = Platforms.PLUG_INS_PLATFORM, layer = Layers.PLATFORM_SERVICE, addon = Addons.ERROR_MANAGER)
@Mock
private ErrorManager errorManager;
@NeededAddonReference(platform = Platforms.PLUG_INS_PLATFORM, layer = Layers.PLATFORM_SERVICE, addon = Addons.EVENT_MANAGER)
@Mock
private EventManager eventManager;
@NeededPluginReference(platform = Platforms.COMMUNICATION_PLATFORM, layer = Layers.COMMUNICATION, plugin = Plugins.WS_CLOUD_CLIENT)
@Mock
private WsCommunicationsCloudClientManager wsCommunicationsCloudClientManager;
@Mock
private TransactionTransmissionPluginRoot transactionTransmissionPluginRoot;
@Mock
private TransactionTransmissionConnectionsDAO transactionTransmissionConnectionsDAO;
@Mock
private TransactionTransmissionContractHashDao transactionTransmissionContractHashDao;
@Mock
private CommunicationNetworkServiceConnectionManager communicationNetworkServiceConnectionManager;
@Mock
private PlatformComponentProfile platformComponentProfile;
@Mock
private List<PlatformComponentProfile> remoteNetworkServicesRegisteredList;
@Mock
private ECCKeyPair eccKeyPair;
@Test
public void Start_ParametersProperlySet_ThreadStarted() throws Exception{
TransactionTransmissionAgent transactionTransmissionAgent = new TransactionTransmissionAgent(
transactionTransmissionPluginRoot,
transactionTransmissionConnectionsDAO,
transactionTransmissionContractHashDao,
communicationNetworkServiceConnectionManager,
wsCommunicationsCloudClientManager,
platformComponentProfile,
errorManager,
remoteNetworkServicesRegisteredList,
eccKeyPair,
eventManager
);
transactionTransmissionAgent.start();
Thread.sleep(100);
assertThat(transactionTransmissionAgent.isRunning()).isTrue();
}
}
| 47.966292 | 169 | 0.821504 |
4fb6532c35b24cbaf5901607452dd1d251a6dc7b | 1,025 | package com.jeiker.retry.service.impl;
import com.jeiker.retry.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import java.time.LocalTime;
/**
* Description: spring-boot2
* User: jeikerxiao
* Date: 2019/1/10 2:58 PM
*/
@Service
@Slf4j
public class UserServiceImpl implements UserService {
@Override
@Retryable(value = {RemoteAccessException.class},
maxAttempts = 3,
backoff = @Backoff(delay = 5000L, multiplier = 1)
)
public void call() throws Exception {
log.info("call(): {} do something...", LocalTime.now());
throw new RemoteAccessException("RPC调用异常");
}
@Recover
public void recover(RemoteAccessException e) {
log.info("recover(): {}", e.getMessage());
}
}
| 27.702703 | 64 | 0.713171 |
a7b941b45a0791766f37dcc02a1b307261ececc5 | 2,604 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/vision/v1p2beta1/image_annotator.proto
package com.google.cloud.vision.v1p2beta1;
public interface AnnotateFileResponseOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.vision.v1p2beta1.AnnotateFileResponse)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Information about the file for which this response is generated.
* </pre>
*
* <code>.google.cloud.vision.v1p2beta1.InputConfig input_config = 1;</code>
*/
boolean hasInputConfig();
/**
*
*
* <pre>
* Information about the file for which this response is generated.
* </pre>
*
* <code>.google.cloud.vision.v1p2beta1.InputConfig input_config = 1;</code>
*/
com.google.cloud.vision.v1p2beta1.InputConfig getInputConfig();
/**
*
*
* <pre>
* Information about the file for which this response is generated.
* </pre>
*
* <code>.google.cloud.vision.v1p2beta1.InputConfig input_config = 1;</code>
*/
com.google.cloud.vision.v1p2beta1.InputConfigOrBuilder getInputConfigOrBuilder();
/**
*
*
* <pre>
* Individual responses to images found within the file.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p2beta1.AnnotateImageResponse responses = 2;</code>
*/
java.util.List<com.google.cloud.vision.v1p2beta1.AnnotateImageResponse> getResponsesList();
/**
*
*
* <pre>
* Individual responses to images found within the file.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p2beta1.AnnotateImageResponse responses = 2;</code>
*/
com.google.cloud.vision.v1p2beta1.AnnotateImageResponse getResponses(int index);
/**
*
*
* <pre>
* Individual responses to images found within the file.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p2beta1.AnnotateImageResponse responses = 2;</code>
*/
int getResponsesCount();
/**
*
*
* <pre>
* Individual responses to images found within the file.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p2beta1.AnnotateImageResponse responses = 2;</code>
*/
java.util.List<? extends com.google.cloud.vision.v1p2beta1.AnnotateImageResponseOrBuilder>
getResponsesOrBuilderList();
/**
*
*
* <pre>
* Individual responses to images found within the file.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p2beta1.AnnotateImageResponse responses = 2;</code>
*/
com.google.cloud.vision.v1p2beta1.AnnotateImageResponseOrBuilder getResponsesOrBuilder(int index);
}
| 27.702128 | 101 | 0.684332 |
d214838ea5ea6f7297e53d59de1354baf2d4f891 | 12,244 | /*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core.jsr.configuration.xml;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.batch.api.BatchProperty;
import javax.batch.api.Batchlet;
import javax.batch.api.chunk.AbstractItemReader;
import javax.batch.api.chunk.AbstractItemWriter;
import javax.batch.api.partition.PartitionPlan;
import javax.batch.api.partition.PartitionPlanImpl;
import javax.batch.runtime.BatchStatus;
import javax.batch.runtime.JobExecution;
import javax.batch.runtime.context.JobContext;
import javax.batch.runtime.context.StepContext;
import javax.inject.Inject;
import org.junit.Before;
import org.junit.Test;
import org.springframework.batch.core.jsr.AbstractJsrTestCase;
import org.springframework.util.Assert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class PartitionParserTests extends AbstractJsrTestCase {
private Pattern caPattern = Pattern.compile("ca");
private Pattern asPattern = Pattern.compile("AS");
private static final long TIMEOUT = 10000L;
@Before
public void before() {
MyBatchlet.processed = new AtomicInteger(0);
MyBatchlet.threadNames = Collections.synchronizedSet(new HashSet<>());
MyBatchlet.artifactNames = Collections.synchronizedSet(new HashSet<>());
PartitionCollector.artifactNames = Collections.synchronizedSet(new HashSet<>());
}
@Test
public void testBatchletNoProperties() throws Exception {
BatchStatus curBatchStatus = runJob("partitionParserTestsBatchlet", new Properties(), TIMEOUT).getBatchStatus();
assertEquals(BatchStatus.COMPLETED, curBatchStatus);
assertEquals(10, MyBatchlet.processed.get());
assertEquals(10, MyBatchlet.threadNames.size());
}
@Test
public void testChunkNoProperties() throws Exception {
JobExecution execution = runJob("partitionParserTestsChunk", new Properties(), TIMEOUT);
assertEquals(BatchStatus.COMPLETED, execution.getBatchStatus());
assertEquals(30, ItemReader.processedItems.size());
assertEquals(10, ItemReader.threadNames.size());
assertEquals(30, ItemWriter.processedItems.size());
assertEquals(10, ItemWriter.threadNames.size());
}
@Test
public void testFullPartitionConfiguration() throws Exception {
JobExecution execution = runJob("fullPartitionParserTests", new Properties(), TIMEOUT);
assertEquals(BatchStatus.COMPLETED, execution.getBatchStatus());
assertTrue(execution.getExitStatus().startsWith("BPS_"));
assertTrue(execution.getExitStatus().endsWith("BPSC_APSC"));
assertEquals(3, countMatches(execution.getExitStatus(), caPattern));
assertEquals(3, countMatches(execution.getExitStatus(), asPattern));
assertEquals(3, MyBatchlet.processed.get());
assertEquals(3, MyBatchlet.threadNames.size());
}
@Test
public void testFullPartitionConfigurationWithProperties() throws Exception {
JobExecution execution = runJob("fullPartitionParserWithPropertiesTests", new Properties(), TIMEOUT);
assertEquals(BatchStatus.COMPLETED, execution.getBatchStatus());
assertTrue(execution.getExitStatus().startsWith("BPS_"));
assertTrue(execution.getExitStatus().endsWith("BPSC_APSC"));
assertEquals(3, countMatches(execution.getExitStatus(), caPattern));
assertEquals(3, countMatches(execution.getExitStatus(), asPattern));
assertEquals(3, MyBatchlet.processed.get());
assertEquals(3, MyBatchlet.threadNames.size());
assertEquals(MyBatchlet.artifactNames.iterator().next(), "batchlet");
assertEquals(PartitionMapper.name, "mapper");
assertEquals(PartitionAnalyzer.name, "analyzer");
assertEquals(PartitionReducer.name, "reducer");
assertEquals(PartitionCollector.artifactNames.size(), 1);
assertTrue(PartitionCollector.artifactNames.contains("collector"));
}
@Test
public void testFullPartitionConfigurationWithMapperSuppliedProperties() throws Exception {
JobExecution execution = runJob("fullPartitionParserWithMapperPropertiesTests", new Properties(), TIMEOUT);
assertEquals(BatchStatus.COMPLETED, execution.getBatchStatus());
assertTrue(execution.getExitStatus().startsWith("BPS_"));
assertTrue(execution.getExitStatus().endsWith("BPSC_APSC"));
assertEquals(3, countMatches(execution.getExitStatus(), caPattern));
assertEquals(3, countMatches(execution.getExitStatus(), asPattern));
assertEquals(3, MyBatchlet.processed.get());
assertEquals(3, MyBatchlet.threadNames.size());
assertEquals(MyBatchlet.artifactNames.size(), 3);
assertTrue(MyBatchlet.artifactNames.contains("batchlet0"));
assertTrue(MyBatchlet.artifactNames.contains("batchlet1"));
assertTrue(MyBatchlet.artifactNames.contains("batchlet2"));
assertEquals(PartitionCollector.artifactNames.size(), 3);
assertTrue(PartitionCollector.artifactNames.contains("collector0"));
assertTrue(PartitionCollector.artifactNames.contains("collector1"));
assertTrue(PartitionCollector.artifactNames.contains("collector2"));
assertEquals(PartitionAnalyzer.name, "analyzer");
assertEquals(PartitionReducer.name, "reducer");
}
@Test
public void testFullPartitionConfigurationWithHardcodedProperties() throws Exception {
JobExecution execution = runJob("fullPartitionParserWithHardcodedPropertiesTests", new Properties(), TIMEOUT);
assertEquals(BatchStatus.COMPLETED, execution.getBatchStatus());
assertTrue(execution.getExitStatus().startsWith("BPS_"));
assertTrue(execution.getExitStatus().endsWith("BPSC_APSC"));
assertEquals(3, countMatches(execution.getExitStatus(), caPattern));
assertEquals(3, countMatches(execution.getExitStatus(), asPattern));
assertEquals(3, MyBatchlet.processed.get());
assertEquals(3, MyBatchlet.threadNames.size());
assertEquals(MyBatchlet.artifactNames.size(), 3);
assertTrue(MyBatchlet.artifactNames.contains("batchlet0"));
assertTrue(MyBatchlet.artifactNames.contains("batchlet1"));
assertTrue(MyBatchlet.artifactNames.contains("batchlet2"));
assertEquals(PartitionCollector.artifactNames.size(), 3);
assertTrue(PartitionCollector.artifactNames.contains("collector0"));
assertTrue(PartitionCollector.artifactNames.contains("collector1"));
assertTrue(PartitionCollector.artifactNames.contains("collector2"));
assertEquals(PartitionMapper.name, "mapper");
assertEquals(PartitionAnalyzer.name, "analyzer");
assertEquals(PartitionReducer.name, "reducer");
}
private int countMatches(String string, Pattern pattern) {
Matcher matcher = pattern.matcher(string);
int count = 0;
while(matcher.find()) {
count++;
}
return count;
}
public static class PartitionReducer implements javax.batch.api.partition.PartitionReducer {
public static String name;
@Inject
@BatchProperty
String artifactName;
@Inject
protected JobContext jobContext;
@Override
public void beginPartitionedStep() throws Exception {
name = artifactName;
jobContext.setExitStatus("BPS_");
}
@Override
public void beforePartitionedStepCompletion() throws Exception {
jobContext.setExitStatus(jobContext.getExitStatus() + "BPSC_");
}
@Override
public void rollbackPartitionedStep() throws Exception {
jobContext.setExitStatus(jobContext.getExitStatus() + "RPS");
}
@Override
public void afterPartitionedStepCompletion(PartitionStatus status)
throws Exception {
jobContext.setExitStatus(jobContext.getExitStatus() + "APSC");
}
}
public static class PartitionAnalyzer implements javax.batch.api.partition.PartitionAnalyzer {
public static String name;
@Inject
@BatchProperty
String artifactName;
@Inject
protected JobContext jobContext;
@Override
public void analyzeCollectorData(Serializable data) throws Exception {
name = artifactName;
Assert.isTrue(data.equals("c"), "Expected c but was " + data);
jobContext.setExitStatus(jobContext.getExitStatus() + data + "a");
}
@Override
public void analyzeStatus(BatchStatus batchStatus, String exitStatus)
throws Exception {
Assert.isTrue(batchStatus.equals(BatchStatus.COMPLETED), String.format("expected %s but received %s", BatchStatus.COMPLETED, batchStatus));
jobContext.setExitStatus(jobContext.getExitStatus() + "AS");
}
}
public static class PartitionCollector implements javax.batch.api.partition.PartitionCollector {
protected static Set<String> artifactNames = Collections.synchronizedSet(new HashSet<>());
@Inject
@BatchProperty
String artifactName;
@Override
public Serializable collectPartitionData() throws Exception {
artifactNames.add(artifactName);
return "c";
}
}
public static class PropertyPartitionMapper implements javax.batch.api.partition.PartitionMapper {
@Override
public PartitionPlan mapPartitions() throws Exception {
Properties[] props = new Properties[3];
for(int i = 0; i < props.length; i++) {
props[i] = new Properties();
props[i].put("collectorName", "collector" + i);
props[i].put("batchletName", "batchlet" + i);
}
PartitionPlan plan = new PartitionPlanImpl();
plan.setPartitions(3);
plan.setThreads(3);
plan.setPartitionProperties(props);
return plan;
}
}
public static class PartitionMapper implements javax.batch.api.partition.PartitionMapper {
public static String name;
@Inject
@BatchProperty
public String artifactName;
@Override
public PartitionPlan mapPartitions() throws Exception {
name = artifactName;
PartitionPlan plan = new PartitionPlanImpl();
plan.setPartitions(3);
plan.setThreads(3);
return plan;
}
}
public static class MyBatchlet implements Batchlet {
protected static AtomicInteger processed = new AtomicInteger(0);;
protected static Set<String> threadNames = Collections.synchronizedSet(new HashSet<>());
protected static Set<String> artifactNames = Collections.synchronizedSet(new HashSet<>());
@Inject
@BatchProperty
String artifactName;
@Inject
StepContext stepContext;
@Inject
JobContext jobContext;
@Override
public String process() throws Exception {
artifactNames.add(artifactName);
threadNames.add(Thread.currentThread().getName());
processed.incrementAndGet();
stepContext.setExitStatus("bad step exit status");
jobContext.setExitStatus("bad job exit status");
return null;
}
@Override
public void stop() throws Exception {
}
}
public static class ItemReader extends AbstractItemReader {
private List<Integer> items;
protected static Vector<Integer> processedItems = new Vector<>();
protected static Set<String> threadNames = Collections.synchronizedSet(new HashSet<>());
@Override
public void open(Serializable checkpoint) throws Exception {
items = new ArrayList<>();
items.add(1);
items.add(2);
items.add(3);
}
@Override
public Object readItem() throws Exception {
threadNames.add(Thread.currentThread().getName());
if(items.size() > 0) {
Integer curItem = items.remove(0);
processedItems.add(curItem);
return curItem;
} else {
return null;
}
}
}
public static class ItemWriter extends AbstractItemWriter {
protected static Vector<Integer> processedItems = new Vector<>();
protected static Set<String> threadNames = Collections.synchronizedSet(new HashSet<>());
@Override
public void writeItems(List<Object> items) throws Exception {
threadNames.add(Thread.currentThread().getName());
for (Object object : items) {
processedItems.add((Integer) object);
}
}
}
}
| 33.271739 | 142 | 0.767233 |
56cf1f68f7c5a462d72e0406b78d7061b5cafcdd | 9,247 | /*
* Copyright (c) 2016, Salesforce.com, 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:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.dva.argus.service;
import com.salesforce.dva.argus.entity.MetricSchemaRecord;
import com.salesforce.dva.argus.entity.MetricSchemaRecordQuery;
import com.salesforce.dva.argus.entity.SchemaQuery;
import com.salesforce.dva.argus.entity.TSDBEntity;
import com.salesforce.dva.argus.service.MonitorService.Counter;
import com.salesforce.dva.argus.service.SchemaService.RecordType;
import com.salesforce.dva.argus.service.schema.WildcardExpansionLimitExceededException;
import com.salesforce.dva.argus.service.tsdb.MetricQuery;
import com.salesforce.dva.argus.util.RequestContextHolder;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
/**
* Provides a means to query metric schema meta data to determine the existence of metrics.
*
* @author Tom Valine ([email protected])
*/
public interface DiscoveryService extends Service {
/** We enforce a soft limit of 1 minute on the datapoint sampling frequency through WardenService and hence assume this
* to be the same. */
static final long DATAPOINT_SAMPLING_FREQ_IN_MILLIS = 60 * 1000L;
static final String EXCEPTION_MESSAGE = "Your query may return more than {0} datapoints in all. Please modify your query. "
+ "You may either reduce the time window or narrow your wildcard search or use downsampling.";
//~ Methods **************************************************************************************************************************************
/**
* Returns a list of metric schema records which match the filtering criteria. At least one field must be filtered.
*
* @param query The query to filter by
* @return A list of metric schema records matching the filtering criteria. Will never return null, but may be empty.
*/
List<MetricSchemaRecord> filterRecords(SchemaQuery query);
/**
* @param query The query
* @param type The field to return. Cannot be null.
* @return A unique list of MetricSchemaRecords. Will never return null, but may be empty.
*/
List<MetricSchemaRecord> getUniqueRecords(MetricSchemaRecordQuery query, RecordType type);
/**
* @param query The query
* @param type The field to return. Cannot be null.
* @param indexLevel The index of the tokenized results to return.
* @return A unique list of tokenized results. Will never return null, but may be empty.
*/
List<String> browseRecords(MetricSchemaRecordQuery query, RecordType type, int indexLevel);
/**
* Expands a given wildcard query into a list of distinct queries.
*
* @param query The wildcard query to expand. Cannot be null.
*
* @return The list of distinct queries representing the wildcard expansion. Will never return null, but may be empty.
*/
List<MetricQuery> getMatchingQueries(MetricQuery query);
/**
* Indicates whether a query is a wildcard query.
*
* @param query The query to evaluate. Cannot be null.
*
* @return True if the query is a wildcard query.
*/
static boolean isWildcardQuery(MetricQuery query) {
if (SchemaService.containsWildcard(query.getScope())
|| SchemaService.containsWildcard(query.getMetric())
|| SchemaService.containsWildcard(query.getNamespace())) {
return true;
}
if (query.getTags() != null) {
for (String tagKey : query.getTags().keySet()) {
if (SchemaService.containsWildcard(tagKey) ||
(!"*".equals(query.getTag(tagKey)) && SchemaService.containsWildcard(query.getTag(tagKey)))) {
return true;
}
}
}
return false;
}
static int maxTimeseriesAllowed(MetricQuery query, long maxDataPointsPerResponse) {
long timeWindowInMillis = getTimeWindowInMillis(query.getStartTimestamp(), query.getEndTimestamp());
// return max datapoints for single second queries
if(timeWindowInMillis<=2000L) {
return (int)maxDataPointsPerResponse;
}
long downsamplingDivisor = (query.getDownsamplingPeriod() == null || query.getDownsamplingPeriod() <= 0) ? 60000l : query.getDownsamplingPeriod();
downsamplingDivisor = (timeWindowInMillis > downsamplingDivisor) ? downsamplingDivisor : timeWindowInMillis;
long samplingPeriod = (downsamplingDivisor>DATAPOINT_SAMPLING_FREQ_IN_MILLIS) ? DATAPOINT_SAMPLING_FREQ_IN_MILLIS : downsamplingDivisor;
double numRawDPsPerSeries = (timeWindowInMillis*1.0)/samplingPeriod;
double numDownsampledDPsPerSeries = (numRawDPsPerSeries) / (downsamplingDivisor/(samplingPeriod*1.0));
numDownsampledDPsPerSeries = numDownsampledDPsPerSeries <= 0 ? 1 : numDownsampledDPsPerSeries;
return (int) (maxDataPointsPerResponse / numDownsampledDPsPerSeries);
}
static long getTimeWindowInMillis(long startTimestamp, long endTimestamp) {
// handling case when start or end timestamp is specified in seconds
if(startTimestamp*1000<System.currentTimeMillis()) {
startTimestamp = startTimestamp*1000;
}
if(endTimestamp*1000<System.currentTimeMillis()) {
endTimestamp = endTimestamp*1000;
}
long timeWindowInMillis = endTimestamp - startTimestamp;
if(timeWindowInMillis>TSDBService.METRICS_RETENTION_PERIOD_MILLIS) {
timeWindowInMillis = TSDBService.METRICS_RETENTION_PERIOD_MILLIS;
}
return timeWindowInMillis;
}
static int numApproxTimeseriesForQuery(MetricQuery mq) {
int count = 1;
for(String tagValue : mq.getTags().values()) {
String splits[] = tagValue.split("\\|");
count *= splits.length;
}
return count;
}
static void throwMaximumDatapointsExceededException(MetricQuery query, long maxDataPointsPerQuery, boolean enforceDatapointLimit, MonitorService monitorService, Logger logger) throws WildcardExpansionLimitExceededException{
if((query.getDownsamplingPeriod()!=null && query.getDownsamplingPeriod()!=0) || enforceDatapointLimit) {
if(monitorService!=null) {
Map<String, String> tags = new HashMap<>();
tags.put("scope", TSDBEntity.replaceUnsupportedChars(query.getScope()));
tags.put("metric", TSDBEntity.replaceUnsupportedChars(query.getMetric()));
if(RequestContextHolder.getRequestContext()!=null) {
tags.put("user", RequestContextHolder.getRequestContext().getUserName());
}else {
tags.put("user", "unknown");
}
monitorService.modifyCounter(Counter.QUERY_DATAPOINTS_LIMIT_EXCEEDED, 1, tags);
logger.error("Maximum datapoints limit execeeded for query - " + query.toString() + ", user - "+tags.get("user"));
}
}
// We are throwing the exception only when the downsampler is absent,
// as we want to give users some time to adjust their queries which have downsampler in them, unless the enforceDatapointLimit flag is true
if(query.getDownsamplingPeriod()==null || query.getDownsamplingPeriod()==0 || enforceDatapointLimit) {
throw new WildcardExpansionLimitExceededException(MessageFormat.format(EXCEPTION_MESSAGE, maxDataPointsPerQuery)) ;
}
}
}
/* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
| 47.178571 | 227 | 0.687466 |
f36eccdab75427ff5cf2d1c0e1cbdbff00e4e2c8 | 214 | package org.bvoid.app.example.gritzer.input;
import org.bvoid.engine.geom.Point2D;
public class DemoCanvasController implements Controller {
@Override
public void mouseDragged(Point2D mousePosition) {}
}
| 16.461538 | 57 | 0.78972 |
5299f05efee07e832a4e460b5aaa0997c874fc67 | 10,461 | /*
* Copyright 2016 Quatico Solutions 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.quatico.base.aem.test.common;
import static com.quatico.base.aem.test.api.AemMatchers.resourceExistsAt;
import static com.quatico.base.aem.test.model.ResourceProperty.NAME;
import static com.quatico.base.aem.test.model.ResourceProperty.TITLE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import com.quatico.base.aem.test.TestDriver;
import com.quatico.base.aem.test.api.setup.Resources;
import com.quatico.base.aem.test.model.ResourceProperty;
import java.util.Iterator;
import javax.jcr.Node;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceMetadata;
import org.junit.Before;
import org.junit.Test;
public abstract class ResourceTestDriver extends TestDriver {
private Resources testObj;
@Before
public void setUp() throws Exception {
this.testObj = new Resources(client);
}
@Test
public void aResourceWithValidPathReturnsResourceWithPath() throws Exception {
String expected = "/content/foobar";
Resource actual = testObj.aResource(expected);
assertEquals(expected, actual.getPath());
}
@Test
public void aResourceWithNonExistingPathReturnsNull() throws Exception {
assertNull(testObj.aResource("DOESNOTEXIST"));
}
@Test
public void aResourceWithSingleSegmentRelativePathReturnsNull() throws Exception {
assertNull(testObj.aResource("path"));
}
@Test
public void aResourceWithNullPathReturnsRootResource() throws Exception {
Resource actual = testObj.aResource(null);
assertEquals("/", actual.getPath());
}
@Test
public void aResourceWithEmptyPathReturnsRootResource() throws Exception {
Resource actual = testObj.aResource(StringUtils.EMPTY);
assertEquals("/", actual.getPath());
}
@Test
public void aResourceWithValidPathAndNoPropertiesYieldsResourceTypeProperty() throws Exception {
Resource actual = testObj.aResource("/content/foobar");
assertEquals("nt:unstructured", actual.adaptTo(Node.class).getProperty(ResourceProperty.PRIMARY_TYPE).getString());
}
@Test
public void aResourceWithValidPathAndPropertiesYieldsNonEmptyProperties() throws Exception {
Resource actual = testObj.aResource("/content/foobar", NAME, "foobar");
Node node = actual.adaptTo(Node.class);
assertEquals("foobar", node.getProperty(NAME).getValue().getString());
}
@Test
public void aResourceWithValidPathAndMultiplePropertiesYieldsCorrectProperties() throws Exception {
Node actual = testObj.aResource("/content/foobar", TITLE, "foobar", ResourceProperty.TEMPLATE, "/libs/foobar/pages/page").adaptTo(Node.class);
assertEquals("/libs/foobar/pages/page", actual.getProperty(ResourceProperty.TEMPLATE).getValue().getString());
assertEquals("foobar", actual.getProperty(TITLE).getValue().getString());
}
@Test
public void getNameWithMultiSegmentPathReturnsLastPathSegment() throws Exception {
Resource target = testObj.aResource("/a/resource/path");
assertEquals("path", target.getName());
}
@Test
public void getNameWithSingleSegmentPathReturnsPathSegment() throws Exception {
Resource target = testObj.aResource("/path");
assertEquals("path", target.getName());
}
@Test
public void getNameWithMultiSegmentRelativePathReturnsLastPathSegment() throws Exception {
Resource target = testObj.aResource("a/resource/path");
assertEquals("path", target.getName());
}
@Test
public void getNameWithNoPathSegmentPathReturnsEmptyString() throws Exception {
Resource target = testObj.aResource("/");
assertEquals("", target.getName());
}
@Test
public void getNameWithNullPathReturnsEmptyString() throws Exception {
Resource target = testObj.aResource(null);
assertEquals(StringUtils.EMPTY, target.getName());
}
@Test
public void getResourceResolverReturnsTheSameInstance() throws Exception {
Resource target = testObj.aResource(null);
assertSame(client.getResourceResolver(), target.getResourceResolver());
}
@Test
public void getParentWithParentReturnsParentResource() throws Exception {
Resource target = testObj.aResource("/content/ko");
Resource actual = target.getParent();
assertThat(actual, resourceExistsAt("/content"));
}
@Test
public void getParentWithNoParentReturnsNull() throws Exception {
Resource target = testObj.aResource("/");
assertNull(target.getParent());
}
@Test
public void getParentWithFirstChildReturnsRootResource() throws Exception {
Resource target = testObj.aResource("/content");
assertEquals("/", target.getParent().getPath());
}
@Test
public void getParentWithParentFindsAllParentResources() throws Exception {
Resource target = testObj.aResource("/content/ko/home");
assertThat(target.getParent(), resourceExistsAt("/content/ko"));
assertThat(target.getParent().getParent(), resourceExistsAt("/content"));
assertEquals("/", target.getParent().getParent().getParent().getPath());
assertNull(target.getParent().getParent().getParent().getParent());
}
@Test
public void getChildrenWithNoChildrenReturnsNoChildren() throws Exception {
testObj.aResource("/content/ko");
Resource target = testObj.aResource("/content/ko/something");
Iterator<Resource> actual = target.getChildren().iterator();
assertFalse(actual.hasNext());
}
@Test
public void getChildrenWithChildrenReturnsAllDirectChildren() throws Exception {
Resource target = testObj.aResource("/content/ko");
testObj.aResource("/content/ko/one");
testObj.aResource("/content/ko/two");
Iterator<Resource> actual = target.getChildren().iterator();
assertEquals("one", actual.next().getName());
assertEquals("two", actual.next().getName());
assertFalse(actual.hasNext());
}
@Test
public void listChildrenWithNoChildrenReturnsNoChildren() throws Exception {
testObj.aResource("/content/ko");
Resource target = testObj.aResource("/content/ko/something");
Iterator<Resource> actual = target.listChildren();
assertFalse(actual.hasNext());
}
@Test
public void listChildrenWithChildrenReturnsAllDirectChildren() throws Exception {
Resource target = testObj.aResource("/content/ko");
testObj.aResource("/content/ko/one");
testObj.aResource("/content/ko/two");
Iterator<Resource> actual = target.listChildren();
assertEquals("one", actual.next().getName());
assertEquals("two", actual.next().getName());
assertFalse(actual.hasNext());
}
@Test
public void listChildrenWithNonExistingResourceReturnsNoChildren() throws Exception {
Resource target = client.getResourceResolver().resolve("DOESNOTEXIST");
Iterator<Resource> actual = target.listChildren();
assertFalse(actual.hasNext());
}
@Test
public void getChildWithNullStringReturnsNull() throws Exception {
Resource target = testObj.aResource("/content");
assertNull(target.getChild(null));
}
@Test
public void getChildWithEmptyStringReturnsNull() throws Exception {
Resource target = testObj.aResource("/content");
assertEquals(target.getPath(), target.getChild("").getPath());
}
@Test
public void getChildWithNonExistingPathReturnsNull() throws Exception {
Resource target = testObj.aResource("/content");
assertNull(target.getChild("DOESNOTEXIST"));
}
@Test
public void getChildWithSameRelativeParentPathReturnsSameResource() throws Exception {
Resource target = testObj.aResource("/content/ko");
testObj.aResource("/content/ko/something");
Resource actual = target.getChild("../ko");
assertEquals(target.getPath(), actual.getPath());
}
@Test
public void getChildWithRelativeChildPathReturnsChildResource() throws Exception {
Resource target = testObj.aResource("/content/ko");
testObj.aResource("/content/ko/something");
Resource actual = target.getChild("./something");
assertThat(actual, resourceExistsAt("/content/ko/something"));
}
@Test
public void getChildWithChildPathReturnsChildResource() throws Exception {
Resource target = testObj.aResource("/content/ko");
testObj.aResource("/content/ko/something");
Resource actual = target.getChild("something");
assertThat(actual, resourceExistsAt("/content/ko/something"));
}
@Test
public void getChildWithRelativePathReturnsChildResource() throws Exception {
Resource target = testObj.aResource("/content");
testObj.aResource("/content/ko");
testObj.aResource("/content/ko/something");
Resource actual = target.getChild("./ko/something");
assertThat(actual, resourceExistsAt("/content/ko/something"));
}
@Test
public void getChildWithPathReturnsResource() throws Exception {
Resource target = testObj.aResource("/content");
testObj.aResource("/content/ko");
testObj.aResource("/content/ko/something");
Resource actual = target.getChild("ko/something");
assertThat(actual, resourceExistsAt("/content/ko/something"));
}
@Test
public void getChildWithAbsolutePathReturnsResource() throws Exception {
Resource target = testObj.aResource("/content");
Resource actual = target.getChild("/content");
assertEquals(target.getPath(), actual.getPath());
}
@Test
public void getResourceMetaDataWithExistingResourceContainsResolutionPathOnly() throws Exception {
Resource target = testObj.aResource("/content");
ResourceMetadata actual = target.getResourceMetadata();
assertEquals("/content", actual.get("sling.resolutionPath"));
}
@Test
public void getResourceWithValidPathReturnsValidResourceWithValidProperties() throws Exception {
Resource target = testObj.aResource("/content/resource");
assertNotNull(target.getValueMap().get(ResourceProperty.PRIMARY_TYPE));
}
} | 31.133929 | 144 | 0.75509 |
5ba6330b621cc0acff2500117ed75632d7a39134 | 2,192 | /*
* Copyright (C) 2012 Zach Melamed
*
* Latest version available online at https://github.com/zach-m/jonix
* Contact me at [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tectonica.jonix.basic;
import java.util.Arrays;
import com.tectonica.jonix.basic.BasicHeader;
import com.tectonica.jonix.onix2.Header;
/**
* ONIX2 concrete implementation for {@link BasicHeader}
*
* @author Zach Melamed
*/
public class BasicHeader2 extends BasicHeader
{
private static final long serialVersionUID = 1L;
public BasicHeader2(Header header)
{
fromCompany = header.getFromCompanyValue();
fromPerson = header.getFromPersonValue();
fromEmail = header.getFromEmailValue();
String toCompany = header.getToCompanyValue();
toCompanies = (toCompany == null) ? null : Arrays.asList(toCompany);
sentDate = header.getSentDateValue();
}
// /**
// * constructor for ONIX3 <Header> element
// */
// public BasicHeader2(com.tectonica.jonix.onix3.Header header)
// {
// fromCompany = header.sender.getSenderNameValue();
// fromPerson = header.sender.getContactNameValue();
// fromEmail = header.sender.getEmailAddressValue();
// toCompanies = extractToCompanies(header);
// sentDate = header.getSentDateTimeValue();
// }
//
// private List<String> extractToCompanies(com.tectonica.jonix.onix3.Header header)
// {
// List<String> list = new ArrayList<>();
// if (header.addressees != null)
// {
// for (Addressee addressee : header.addressees)
// {
// String toCompany = addressee.getAddresseeNameValue();
// if (toCompany != null)
// list.add(toCompany);
// }
// }
// return list.size() > 0 ? list : null;
// }
}
| 30.027397 | 83 | 0.716241 |
95459fd63139b449a0071bddd793bd2dd04b90cc | 270 | package com.jtt.hhl.service;
/**
* @Description: META-INF.dubbo service接口
* @Author: Herman
* @CreateDate: 2019/1/5 10:48
*/
public interface TestDubboService {
/**
* 测试接口
* @param arg
* @return
*/
String testDubboService(String arg);
}
| 16.875 | 41 | 0.618519 |
3bada3c3b1880ac75eca386763b355f18cb6ab31 | 967 | package com.yaowei.ncov.module;
import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.impl.NutIoc;
import org.nutz.ioc.loader.combo.ComboIocLoader;
/**
* 这个类做出来是给jsp获取ioc,dao用的。
* 但是发现这个做法可能导致异常 com.alibaba.druid.pool.DataSourceClosedException: dataSource already closed
* 使用另外的方法更佳节。
* https://nutz.cn/yvr/t/10hds3086qgj3odo9769b84ulc
* http://nutzam.com/core/ioc/ioc_by_hand.html
* @author xici
*
*/
public class StaticModule {
private Dao dao=null;
public StaticModule(){
try {
Ioc ioc=new NutIoc(new ComboIocLoader("*js", "ioc/", "*anno", "com.yaowei.ncov"));
dao = ioc.get(Dao.class);
/*
if(dao==null){
System.out.println("dao is null in j");
}else{
System.out.println("dao is not null in j");
}
*/
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Dao getDao(){
return dao;
}
}
| 21.488889 | 94 | 0.649431 |
b2a52bf3c10120a2938103a309cab3062fe2fe64 | 2,364 | package info.hiergiltdiestfu.aws.neptune.graphml;
import java.io.IOException;
import javax.xml.bind.JAXBException;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.graphdrawing.graphml.xmlns.EdgeType;
import org.graphdrawing.graphml.xmlns.NodeType;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import info.hiergiltdiestfu.aws.neptune.graphml.createdatabase.RefactorGraph;
/**
* Class to show that negative Parameters will not work I use Mockito to see if
* functions are called correctly, regardless of the parameter passed. In
* addition, Mockito helps classes to capsules and check them independently.
*
* @author LUNOACK
*
*/
public class NegativeFunctionTests {
/**
* Database which tests our functions
*/
private static GraphTraversalSource g;
private static Graph graph;
/**
* The class which builts the new Database.
*/
private static RefactorGraph built;
/**
* Creates a Test-Database.
*
* @throws IOException
* @throws JAXBException
*/
@BeforeAll
static void setup() throws IOException, JAXBException {
graph = Mockito.mock(Graph.class);
built = new RefactorGraph("8182", "localhost");
graph = TinkerGraph.open();
g = graph.traversal();
}
/**
* Multiple ID´s will give Exceptions
*/
@Test
void testVertexId() {
NodeType node1 = new NodeType();
node1.setId("1");
built.extractNode(node1, g);
Assertions.assertThrows(IllegalArgumentException.class, () -> {
NodeType node2 = new NodeType();
node2.setId("1");
built.extractNode(node2, g);
});
}
/**
* Edge Sources of Verticies which are not existent will give Exceptions
*/
@Test
void testEdgeTargetSource() {
EdgeType edge = new EdgeType();
Assertions.assertThrows(NullPointerException.class, () -> {
built.extractEdge(edge, g);
});
edge.setSource("3");
edge.setTarget("4");
Assertions.assertThrows(IllegalArgumentException.class, () -> {
built.extractEdge(edge, g);
});
edge.setSource("1");
edge.setTarget("");
Assertions.assertThrows(IllegalArgumentException.class, () -> {
built.extractEdge(edge, g);
});
}
}
| 24.884211 | 85 | 0.728849 |
c3915944d923662d2559cc94e750b412f0748afa | 160 | package org.apache.hadoop.corona;
import java.util.List;
public interface SessionListener {
public void notifyGrantResource(List<ResourceGrant> granted);
}
| 20 | 63 | 0.80625 |
60012495344e1da7e19a505987173f2a7c6a5083 | 105 | package com.androthink.server.callback;
public interface ServerCallBack {
void onServerStopped();
}
| 17.5 | 39 | 0.780952 |
3a2684f195d5961fbf0ca2d95fbf7662af1de877 | 810 | package com.tiny.demo.firstlinecode.kfysts.chapter02;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.tiny.demo.firstlinecode.R;
import com.tinytongtong.tinyutils.LogUtils;
public class Chapter02ThirdActivity extends AppCompatActivity {
public static void actionStart(Context context) {
Intent intent = new Intent(context, Chapter02ThirdActivity.class);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter02_third);
LogUtils.INSTANCE.e("MultipleProcessActivity Third", "sUserId --> " + MultipleProcessActivity.sUserId);
}
}
| 33.75 | 111 | 0.766667 |
9232c2bf1403626a1f2e0e194c5e34ec0ec75eac | 124 | package ro.training.java.c06._04_lambda;
public interface SomeStringFunction {
String operateOnString(String input);
}
| 20.666667 | 41 | 0.798387 |
44368913043e37ae0bcd0e64d201388d12045641 | 2,600 | package vital.splitspace.contentManagement;
import java.util.ArrayList;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import vital.splitspace.drawable.Drawable;
import vital.splitspace.entity.Entity;
import vital.splitspace.entity.PlayerBullet;
import vital.splitspace.entity.Ship;
/**
* The Overseer handles all additions and deletions of objects in
* one place. This avoids memory leaks and null references.
*/
public class Overseer
{
// We'll need to keep certain things seperate to optimize
// some checks.
private ArrayList<Entity> entities;
private ArrayList<Drawable> drawables;
private ArrayList<Entity> enemies;
private ArrayList<PlayerBullet> playerBullets;
private Ship player;
public Overseer()
{
this.entities = new ArrayList<>();
this.drawables = new ArrayList<>();
this.enemies = new ArrayList<>();
this.playerBullets = new ArrayList<>();
return;
}
/**
* Removes an Entity from all lists it is contained in.
*
* @param e The Entity to remove.
*/
public void removeEntity(Entity e)
{
this.entities.remove(e);
if (e instanceof Drawable)
this.drawables.remove(e);
//this.enemies.remove(e);
if (e instanceof PlayerBullet)
this.playerBullets.remove(e);
if (this.player == e)
this.player = null;
return;
}
/**
* Adds a new Entity to all categories it should belong to.
*
* @param e The Entity to add.
*/
public void addEntity(Entity e)
{
this.entities.add(e);
if (e instanceof Drawable)
this.drawables.add((Drawable) e);
if (e instanceof PlayerBullet)
this.playerBullets.add((PlayerBullet) e);
//else if (e instanceof Enemy)
// this.enemies.add(e)
else if (e instanceof Ship)
this.player = (Ship) e;
return;
}
public void draw(GameContainer game, Graphics gfx)
{
for (Drawable d : this.drawables)
d.draw(game, gfx);
return;
}
public void update(Input input)
{
// The player shot a bullet
if (input.isKeyPressed(Input.KEY_SPACE))
{
PlayerBullet b = new PlayerBullet();
b.setPosition(player.getPosition());
addEntity(b);
}
// Concurrent manipulation of a list isn't supported in Java,
// so we make a new list to temporarily hold all items that
// must be removed.
ArrayList<Entity> toRemove = new ArrayList<>();
for (Entity e : this.entities)
{
if (e.needToDestroy())
toRemove.add(e);
else
e.update(input);
}
// Remove the items that requested to be destroyed.
for (Entity e : toRemove)
removeEntity(e);
return;
}
}
| 21.666667 | 65 | 0.69 |
8088f16cf89d342e9b4bff4381d4c7d869fd37db | 1,425 | /**
* This file was auto-generated by the Titanium Module SDK helper for Android
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2018 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*
*/
package ti.osm;
import org.appcelerator.kroll.KrollModule;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiApplication;
@Kroll.module(name = "TiOsm", id = "ti.osm")
public class TiOsmModule extends KrollModule
{
@Kroll.constant
public static final int MAPNIK = 0;
@Kroll.constant
public static final int WIKIMEDIA = 1;
@Kroll.constant
public static final int PUBLIC_TRANSPORT = 2;
@Kroll.constant
public static final int CLOUDMADESTANDARDTILES = 3;
@Kroll.constant
public static final int CLOUDMADESMALLTILES = 4;
@Kroll.constant
public static final int FIETS_OVERLAY_NL = 5;
@Kroll.constant
public static final int BASE_OVERLAY_NL = 6;
@Kroll.constant
public static final int ROADS_OVERLAY_NL = 7;
@Kroll.constant
public static final int HIKEBIKEMAP = 8;
@Kroll.constant
public static final int OPEN_SEAMAP = 9;
@Kroll.constant
public static final int USGS_TOPO = 10;
@Kroll.constant
public static final int USGS_SAT = 11;
public TiOsmModule()
{
super();
}
@Kroll.onAppCreate
public static void onAppCreate(TiApplication app)
{
}
}
| 26.886792 | 77 | 0.765614 |
5432b8ff4c8e7887e14d6c53a0c7b9af54f403b7 | 2,287 | /*
* Copyright 2018-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.odtn.utils.openconfig;
import org.onosproject.yang.gen.v1.openconfigterminaldevice.rev20161222.openconfigterminaldevice.terminallogicalchanassignmenttop.DefaultLogicalChannelAssignments;
/**
* Utility class to deal with OPENCONFIG LogicalChannelAssignments ModelObject & Annotation.
*/
public final class OpenConfigLogicalChannelAssignmentsHandler
extends OpenConfigObjectHandler<DefaultLogicalChannelAssignments> {
private static final String OPENCONFIG_NAME = "logical-channel-assignments";
private static final String NAME_SPACE = "http://openconfig.net/yang/terminal-device";
/**
* OpenConfigLogicalChannelAssignmentsHandler Constructor.
*
* @param parent OpenConfigChannelHandler of parent OPENCONFIG(channel)
*/
public OpenConfigLogicalChannelAssignmentsHandler(OpenConfigChannelHandler parent) {
modelObject = new DefaultLogicalChannelAssignments();
setResourceId(OPENCONFIG_NAME, NAME_SPACE, null, parent.getResourceIdBuilder());
annotatedNodeInfos = parent.getAnnotatedNodeInfoList();
parent.addLogicalChannelAssignments(this);
}
/**
* Add Assignment to modelObject of target OPENCONFIG.
*
* @param assignment OpenConfigAssignmentHandler having Assignment to be set for modelObject
* @return OpenConfigLogicalChannelAssignmentsHandler of target OPENCONFIG
*/
public OpenConfigLogicalChannelAssignmentsHandler addAssignment(
OpenConfigAssignmentHandler assignment) {
modelObject.addToAssignment(assignment.getModelObject());
return this;
}
}
| 42.351852 | 163 | 0.752514 |
b51ba7d96562a08aeffd2c76d48a193679ba5a0d | 319 | package com.google.engedu.wordladder;
/**
* Created by Ajacob2609 on 6/19/2017.
*/
public class WordNode {
String word;
int numSteps;
WordNode pre;
public WordNode(String word, int numSteps, WordNode pre){
this.word = word;
this.numSteps = numSteps;
this.pre = pre;
}
}
| 17.722222 | 61 | 0.623824 |
8de9b6b01c581a3029e8701e521ceebbd8da90ae | 4,360 | /*
* Copyright 2016 Bill Bejeck
*
* 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 bbejeck.streams.purchases;
import bbejeck.model.Purchase;
import bbejeck.model.PurchasePattern;
import bbejeck.model.RewardAccumulator;
import bbejeck.serializer.JsonDeserializer;
import bbejeck.serializer.JsonSerializer;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KStreamBuilder;
import org.apache.kafka.streams.processor.WallclockTimestampExtractor;
import java.util.Properties;
/**
* User: Bill Bejeck
* Date: 3/7/16
* Time: 5:34 PM
*/
public class PurchaseKafkaStreamsDriver {
public static void main(String[] args) {
StreamsConfig streamsConfig = new StreamsConfig(getProperties());
JsonDeserializer<Purchase> purchaseJsonDeserializer = new JsonDeserializer<>(Purchase.class);
JsonSerializer<Purchase> purchaseJsonSerializer = new JsonSerializer<>();
JsonSerializer<RewardAccumulator> rewardAccumulatorJsonSerializer = new JsonSerializer<>();
JsonDeserializer<RewardAccumulator> rewardAccumulatorJsonDeserializer = new JsonDeserializer<>(RewardAccumulator.class);
Serde<RewardAccumulator> rewardAccumulatorSerde = Serdes.serdeFrom(rewardAccumulatorJsonSerializer,rewardAccumulatorJsonDeserializer);
JsonSerializer<PurchasePattern> purchasePatternJsonSerializer = new JsonSerializer<>();
JsonDeserializer<PurchasePattern> purchasePatternJsonDeserializer = new JsonDeserializer<>(PurchasePattern.class);
Serde<PurchasePattern> purchasePatternSerde = Serdes.serdeFrom(purchasePatternJsonSerializer,purchasePatternJsonDeserializer);
Serde<Purchase> purchaseSerde = Serdes.serdeFrom(purchaseJsonSerializer,purchaseJsonDeserializer);
StringDeserializer stringDeserializer = new StringDeserializer();
StringSerializer stringSerializer = new StringSerializer();
Serde<String> stringSerde = Serdes.serdeFrom(stringSerializer,stringDeserializer);
KStreamBuilder kStreamBuilder = new KStreamBuilder();
KStream<String,Purchase> purchaseKStream = kStreamBuilder.stream(stringSerde,purchaseSerde,"src-topic")
.mapValues(p -> Purchase.builder(p).maskCreditCard().build());
purchaseKStream.mapValues(purchase -> PurchasePattern.builder(purchase).build()).to(stringSerde,purchasePatternSerde,"patterns");
purchaseKStream.mapValues(purchase -> RewardAccumulator.builder(purchase).build()).to(stringSerde,rewardAccumulatorSerde,"rewards");
purchaseKStream.to(stringSerde,purchaseSerde,"purchases");
System.out.println("Starting PurchaseStreams Example");
KafkaStreams kafkaStreams = new KafkaStreams(kStreamBuilder,streamsConfig);
kafkaStreams.start();
System.out.println("Now started PurchaseStreams Example");
}
private static Properties getProperties() {
Properties props = new Properties();
props.put(StreamsConfig.CLIENT_ID_CONFIG, "Example-Kafka-Streams-Job");
props.put("group.id", "streams-purchases");
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "testing-streams-api");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
props.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 1);
props.put(StreamsConfig.TIMESTAMP_EXTRACTOR_CLASS_CONFIG, WallclockTimestampExtractor.class);
return props;
}
}
| 42.330097 | 142 | 0.768578 |
0585215486e98c5e0ef4da65b9d7369e2ae97170 | 420 | package net.thesimpleteam.jrevolt.event;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ServerDeletedEvent implements Event {
@Expose
@SerializedName("id")
private final String serverId;
public ServerDeletedEvent(String serverId) {
this.serverId = serverId;
}
public String getServerId() {
return serverId;
}
}
| 21 | 50 | 0.719048 |
f4dbf5cc3a9f9ec965425bf249f9b15c6463c8e5 | 4,774 | package pm.n2.parachute.render;
import com.google.gson.JsonObject;
import com.mojang.blaze3d.systems.RenderSystem;
import fi.dy.masa.malilib.util.JsonUtils;
import fi.dy.masa.malilib.util.PositionUtils;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.Matrix4f;
import net.minecraft.util.math.Vec3d;
import java.util.ArrayList;
import java.util.List;
public class RenderContainer {
public static final RenderContainer INSTANCE = new RenderContainer();
private final List<OverlayRendererBase> renderers = new ArrayList<>();
protected boolean resourcesAllocated;
protected int countActive;
private RenderContainer() {
this.addRenderer(new OverlayRendererWorldEditCUI());
}
private void addRenderer(OverlayRendererBase renderer) {
if (this.resourcesAllocated) {
renderer.allocateGlResources();
}
this.renderers.add(renderer);
}
public void render(Entity entity, MatrixStack matrixStack, Matrix4f projMatrix, MinecraftClient mc) {
Vec3d cameraPos = mc.gameRenderer.getCamera().getPos();
this.update(cameraPos, matrixStack, entity, mc);
this.draw(cameraPos, matrixStack, projMatrix, mc);
}
protected void update(Vec3d cameraPos, MatrixStack matrixStack, Entity entity, MinecraftClient mc) {
this.allocateResourcesIfNeeded();
this.countActive = 0;
for (OverlayRendererBase renderer : this.renderers) {
if (renderer.shouldRender(mc)) {
if (renderer.needsUpdate(entity, mc)) {
renderer.lastUpdatePos = PositionUtils.getEntityBlockPos(entity);
renderer.setUpdatePosition(cameraPos);
renderer.update(cameraPos, matrixStack, entity, mc);
}
++this.countActive;
}
}
}
protected void draw(Vec3d cameraPos, MatrixStack matrixStack, Matrix4f projMatrix, MinecraftClient mc) {
if (this.resourcesAllocated && this.countActive > 0) {
RenderSystem.disableTexture();
RenderSystem.disableCull();
RenderSystem.enableDepthTest();
RenderSystem.depthMask(false);
RenderSystem.polygonOffset(-3f, -3f);
RenderSystem.enablePolygonOffset();
fi.dy.masa.malilib.render.RenderUtils.setupBlend();
fi.dy.masa.malilib.render.RenderUtils.color(1f, 1f, 1f, 1f);
for (IOverlayRenderer renderer : this.renderers) {
if (renderer.shouldRender(mc)) {
Vec3d updatePos = renderer.getUpdatePosition();
matrixStack.push();
matrixStack.translate(updatePos.x - cameraPos.x, updatePos.y - cameraPos.y, updatePos.z - cameraPos.z);
renderer.draw(matrixStack, projMatrix);
matrixStack.pop();
}
}
RenderSystem.polygonOffset(0f, 0f);
RenderSystem.disablePolygonOffset();
fi.dy.masa.malilib.render.RenderUtils.color(1f, 1f, 1f, 1f);
RenderSystem.disableBlend();
RenderSystem.enableDepthTest();
RenderSystem.enableCull();
RenderSystem.depthMask(true);
RenderSystem.enableTexture();
}
}
protected void allocateResourcesIfNeeded() {
if (!this.resourcesAllocated) {
this.deleteGlResources();
this.allocateGlResources();
}
}
protected void allocateGlResources() {
if (!this.resourcesAllocated) {
for (OverlayRendererBase renderer : this.renderers) {
renderer.allocateGlResources();
}
this.resourcesAllocated = true;
}
}
protected void deleteGlResources() {
if (this.resourcesAllocated) {
for (OverlayRendererBase renderer : this.renderers) {
renderer.deleteGlResources();
}
this.resourcesAllocated = false;
}
}
public JsonObject toJson() {
JsonObject obj = new JsonObject();
for (OverlayRendererBase renderer : this.renderers) {
String id = renderer.getSaveId();
if (!id.isEmpty()) {
obj.add(id, renderer.toJson());
}
}
return obj;
}
public void fromJson(JsonObject obj) {
for (OverlayRendererBase renderer : this.renderers) {
String id = renderer.getSaveId();
if (!id.isEmpty() && JsonUtils.hasObject(obj, id)) {
renderer.fromJson(obj.get(id).getAsJsonObject());
}
}
}
}
| 32.924138 | 123 | 0.616045 |
b888f706c6b5033071d0dc348f56806188b5e6a6 | 12,191 | package com.solibri.smc.api.examples.beginner;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.image.BufferedImage;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import com.solibri.geometry.linearalgebra.MVector3d;
import com.solibri.geometry.linearalgebra.Vector2d;
import com.solibri.geometry.linearalgebra.Vector3d;
import com.solibri.geometry.primitive2d.AABB2d;
import com.solibri.geometry.primitive2d.Area;
import com.solibri.geometry.primitive2d.MAABB2d;
import com.solibri.geometry.primitive2d.Polygon2d;
import com.solibri.geometry.primitive3d.AABB3d;
import com.solibri.smc.api.SMC;
import com.solibri.smc.api.checking.DoubleParameter;
import com.solibri.smc.api.checking.FilterParameter;
import com.solibri.smc.api.checking.OneByOneRule;
import com.solibri.smc.api.checking.Result;
import com.solibri.smc.api.checking.ResultFactory;
import com.solibri.smc.api.checking.RuleParameters;
import com.solibri.smc.api.checking.RuleResources;
import com.solibri.smc.api.filter.AABBIntersectionFilter;
import com.solibri.smc.api.filter.ComponentFilter;
import com.solibri.smc.api.model.Component;
import com.solibri.smc.api.model.PropertyType;
import com.solibri.smc.api.ui.UIContainer;
import com.solibri.smc.api.visualization.Bitmap;
/**
* Example rule template that uses Bitmap visualization to visualize heatmap.
*/
public class HeatmapVisualizationRule extends OneByOneRule {
/**
* Light blue color for heatmap visualization.
*/
private static final Color VISUALIZATION_COLOR = new Color(100, 100, 255);
/**
* Resolution of the bitmap.
*/
private static final int BITMAP_RESOLUTION = 1600;
/**
* Maximum number of the heatmap color steps used.
*/
private static final int STEP_LIMIT = 50;
/**
* Retrieve the parameter creation handler, used to define parameters for
* this rule.
*/
private final RuleParameters params = RuleParameters.of(this);
/**
* Retrieve the default filter.
* Every component that passes the filter is then forwarded to
* the {@link OneByOneRule#check(Component, ResultFactory)} method.
*/
final FilterParameter rpComponentFilter = this.getDefaultFilterParameter();
/**
* The second filter for the effect components.
*/
final FilterParameter rpEffectSourceFilter = params.createFilter("rpEffectSourceFilter");
/**
* A DoubleParameter allows the user to input a double value that in this
* case defines the range of the heatmap from the source component. The
* PropertyType is used to correctly format the double value when displayed
* in the UI. E.g. when selecting PropertyType.Length the value "5.0" will
* be formatted as follows: "5.0 m".
*/
final DoubleParameter rpRangeParameter = params.createDouble("rpRange", PropertyType.LENGTH);
/**
* The second DoubleParameter for the length of the step.
*/
final DoubleParameter rpStepParameter = params.createDouble("rpStep", PropertyType.LENGTH);
/**
* Add the UI definition.
*/
private final HeatmapVisualizationRuleUIDefinition uiDefinition = new HeatmapVisualizationRuleUIDefinition(this);
/**
* This method is called for every component that passes through the default filter
*
* @param component the component to check
*/
@Override
public Collection<Result> check(Component component, ResultFactory resultFactory) {
/*
* A rule parameter value can be accessed by calling the corresponding
* method.
*/
double range = rpRangeParameter.getValue();
ComponentFilter rangeFilter = rpEffectSourceFilter.getValue();
/*
* Get the components within range by creating a filter that returns the components whose bounding boxes
* are within the given range of the checked component's axis-aligned bounding box.
*/
ComponentFilter componentsInRangeFilter = AABBIntersectionFilter.ofComponentBounds(component, range, 0.0)
.and(rangeFilter);
Collection<Component> componentsInRange = SMC.getModel().getComponents(componentsInRangeFilter);
/*
* Discard the checking if the range-value doesn't meet the requirements
* or there are no effect sources in range.
*/
if (range <= 0.0 || componentsInRange.isEmpty()) {
// No result produced
return Collections.emptySet();
}
/*
* Create the bitmap that contains the heatmap.
*/
Bitmap bitmap = createBitmapVisualization(component, componentsInRange);
/*
* Create the result.
*/
Result result = createResult(component, componentsInRange, bitmap, resultFactory);
/*
* Return the one result created for this component.
*/
return Collections.singleton(result);
}
private Result createResult(Component component, Collection<Component> componentsInRange, Bitmap bitmap,
ResultFactory resultFactory) {
/*
* Create the name and description for this result.
*/
String resultName = createResultName(component);
String resultDescription = createResultDescription(componentsInRange);
/*
* Results are created with the result factory. At least a name and description are required to create a result.
* The result will be attached to the component we are now checking.
*/
return resultFactory
.create(resultName, resultDescription)
/*
* When creating a result it's important to remember to add the other involved components
* to the result so that those will be visible in the UI.
*/
.withInvolvedComponents(componentsInRange)
/*
* A custom visualization for the result can be created.
*/
.withVisualization(visualization -> {
/*
* Add the bitmap to the visualization of the result.
*/
visualization.addVisualizationItem(bitmap);
/*
* Add the component with 75% transparency to the visualization of the
* result.
*/
visualization.addComponent(component, 0.75);
/*
* Add the effect-sources with no (0%) transparency to the visualization
* of the result.
*/
visualization.addComponents(componentsInRange, 0.0);
});
}
private String createResultName(Component component) {
return component.getName();
}
private String createResultDescription(Collection<Component> componentsInRange) {
/*
* getString() allows user to handle the localized string(s) mapped by
* the key(s).
*/
String descriptionHeadline = RuleResources.of(this).getString("resultDescription", componentsInRange.size());
/*
* Create the result description that contains the unique identifiers of
* the components listed below the description headline. By using the html
* you can modify the outlook of the description.
*/
StringBuilder resultDescription = new StringBuilder(descriptionHeadline);
final String htmlBrTag = "<br>";
resultDescription.append(htmlBrTag);
for (Component componentInRange : componentsInRange) {
String displayName = componentInRange.getName();
resultDescription.append(htmlBrTag);
resultDescription.append(displayName);
}
return resultDescription.toString();
}
private Bitmap createBitmapVisualization(Component component, Collection<Component> componentsInRange) {
/*
* Initialize the graphics based on the area of the component.
*/
Area area = component.getFootprint().getArea();
MAABB2d boundingRectangle = area.getBoundingRectangle();
int imageType = BufferedImage.TYPE_INT_ARGB;
BufferedImage image = new BufferedImage(BITMAP_RESOLUTION, BITMAP_RESOLUTION, imageType);
Graphics2D graphics = createImageGraphics(image, boundingRectangle);
graphics.setClip(createComponentShape(component));
/*
* Draw the heatmap and effect-source into 2D-graphics for each component
* in the range.
*/
for (Component entityInRange : componentsInRange) {
Shape shape = createComponentShape(entityInRange);
drawHeatmap2D(graphics, rpRangeParameter.getValue(), rpStepParameter.getValue(), shape);
drawEffectSource2D(graphics, shape);
}
/*
* This method returns the minimum size axis-aligned bounding box of the
* component.
*/
AABB3d componentBounds = component.getBoundingBox();
/*
* VisualizationItemFactory allows the user to create visualization
* items.
*/
MVector3d location = boundingRectangle.getCentroid().to3dVector();
double zOffsetToAvoidOverlapping = 0.03;
location.setZ(componentBounds.getLowerBound().getZ() + zOffsetToAvoidOverlapping);
double bitmapWidth = boundingRectangle.getSizeX();
double bitmapHeight = boundingRectangle.getSizeY();
return Bitmap.create(image, Vector3d.UNIT_Z, Vector3d.UNIT_Y, location, bitmapWidth, bitmapHeight);
}
private static AffineTransform createWorldToImageTransformation(AABB2d boundingRectangle) {
AffineTransform affineTransform = new AffineTransform();
double scaleX = BITMAP_RESOLUTION / boundingRectangle.getSizeX();
double scaleY = BITMAP_RESOLUTION / boundingRectangle.getSizeY();
affineTransform.scale(scaleX, scaleY);
Vector2d offset = boundingRectangle.getLowerBound();
double offsetX = -offset.getX();
double offsetY = -offset.getY();
affineTransform.translate(offsetX, offsetY);
return affineTransform;
}
private static Graphics2D createImageGraphics(BufferedImage image, MAABB2d boundingRectangle) {
AffineTransform affineTransform = createWorldToImageTransformation(boundingRectangle);
Graphics2D graphics = image.createGraphics();
graphics.setTransform(affineTransform);
graphics.setColor(VISUALIZATION_COLOR);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
return graphics;
}
private static void drawHeatmap2D(Graphics2D imageGraphics, double range, double step, Shape shape) {
boolean drawSteps = step < range && step > 0 && (range / step) < STEP_LIMIT;
int stepsCount = drawSteps ? (int) Math.floor(range / step) : 0;
float alpha = drawSteps ? 1f / (stepsCount + 1) : 0.25f;
setAlphaComposite(imageGraphics, alpha);
/*
* Draw heatmap from the edge of the source component to the distance of
* given range.
*/
drawShapeWithOffset(imageGraphics, shape, (float) range);
/*
* Draw the heatmap steps if needed. Draw the steps from the edge of the
* source component. Steps divides the drawn heatmap range area to
* multiple slices (steps).
*/
if (drawSteps) {
for (int i = 1; i <= stepsCount; i++) {
float offset = (float) step * i;
drawShapeWithOffset(imageGraphics, shape, offset);
}
}
}
private static void drawEffectSource2D(Graphics2D graphics, Shape shape) {
setAlphaComposite(graphics, 1f);
graphics.fill(shape);
drawShapeWithOffset(graphics, shape, 0.0f);
}
private static void setAlphaComposite(Graphics2D graphics, float alpha) {
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
}
private static void drawShapeWithOffset(Graphics2D graphics, Shape shape, float offset) {
/*
* Increase the size of the shape with amount of offset-value. This is
* done by increasing the line thickness. The line thickness is twice
* the offset because it effects on both sides from the line.
*/
float edgeThickness = 2.0f * offset;
graphics.setStroke(new BasicStroke(edgeThickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
0.0f, null, 0.0f));
graphics.draw(shape);
}
private Shape createComponentShape(Component component) {
/*
* Get the outline polygon of the footprint because we just need to have
* the outer polygon of the footprint.
*/
Polygon2d footprint = component.getFootprint().getOutline();
/*
* Create the GeneralPath (java.awt.geom.Shape) of the footprint.
*/
GeneralPath path = new GeneralPath();
List<Vector2d> vertices = footprint.getVertices();
for (int i = 0; i < vertices.size(); i++) {
Vector2d point = vertices.get(i);
if (i == 0) {
path.moveTo(point.getX(), point.getY());
} else {
path.lineTo(point.getX(), point.getY());
}
}
path.closePath();
return path;
}
@Override
public UIContainer getParametersUIDefinition() {
return uiDefinition.getDefinitionContainer();
}
}
| 34.053073 | 114 | 0.75162 |
380c3d62898065ca9aecfcf1d554792d0ca650e2 | 647 | package com.flixned.streamingservice.services;
import com.flixned.streamingservice.common.models.Stream;
import com.flixned.streamingservice.repositories.StreamRepository;
import org.springframework.stereotype.Service;
@Service
public class StreamService {
private final StreamRepository streamRepository;
public StreamService(StreamRepository streamRepository) {
this.streamRepository = streamRepository;
}
public Iterable<Stream> allStreams() {
return streamRepository.findAll();
}
public Stream getStream(String contentId) {
return streamRepository.getStreamByContentId(contentId);
}
}
| 26.958333 | 66 | 0.772798 |
4d024a7b81bd125f4e6d8931bc9b0cae87882127 | 98 | /**
* Data Access Objects used by WebSocket services.
*/
package com.quizzly.web.websocket.dto;
| 19.6 | 50 | 0.734694 |
7668912ca1758a245d847cea0df86226547a5824 | 1,397 | package com.bazl.dna.caseinfo.reg.controller.delegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.bazl.dna.caseinfo.reg.common.Constants;
import com.bazl.dna.lims.model.po.LoaUserInfo;
import com.bazl.dna.lims.service.LoaUserInfoService;
/**
* Created by Administrator on 2018/12/24.
*/
@Controller
@RequestMapping("/LoaUserInfoController")
public class LoaUserInfoController {
@Autowired
private LoaUserInfoService loaUserInfoService;
/**
* 禁用登录用户
* @param loaUserInfo
* @return
*/
@RequestMapping("forbiddenLoaUserInfo")
public String forbiddenLoaUserInfo(LoaUserInfo loaUserInfo){
//根据PersonalId修改LOA_USER_INFO中的ActiveFlag状态为"1"
loaUserInfoService.forbiddenLoaUserInfo(loaUserInfo.getPersonalId(), Constants.user_active_flase);
return "redirect:/manage/delegatorManage";
}
/**
* 启用登录用户
* @param loaUserInfo
* @return
*/
@RequestMapping("startusingLoaUserInfo")
public String startusingLoaUserInfo(LoaUserInfo loaUserInfo){
//根据PersonalId修改LOA_USER_INFO中的ActiveFlag状态为"0"
loaUserInfoService.startusingLoaUserInfo(loaUserInfo.getPersonalId(), Constants.user_active_true);
return "redirect:/manage/delegatorManage";
}
}
| 33.261905 | 106 | 0.753042 |
317c09292f03fb939e8847c8c78faa7124ad0e40 | 3,803 | package com.ms_square.etsyblur;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
/**
* ViewUtil.java
*
* @author Manabu-GT on 6/12/14.
*/
public final class ViewUtil {
public static final boolean IS_POST_HONEYCOMB_MR1 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
public static Bitmap drawViewToBitmap(View view, int width, int height, int downScaleFactor, @ColorInt int overlayColor) {
return drawViewToBitmap(view, width, height, 0f, 0f, downScaleFactor, overlayColor);
}
public static Bitmap drawViewToBitmap(View view, int width, int height, float translateX,
float translateY, int downScaleFactor, @ColorInt int overlayColor) {
if (downScaleFactor <= 0) {
throw new IllegalArgumentException("downSampleFactor must be greater than 0.");
}
// check whether valid width/height is given to create a bitmap
if (width <= 0 || height <= 0) {
return null;
}
int bmpWidth = (int) ((width - translateX) / downScaleFactor);
int bmpHeight = (int) ((height - translateY) / downScaleFactor);
Bitmap dest = Bitmap.createBitmap(bmpWidth, bmpHeight, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(dest);
c.translate(-translateX / downScaleFactor, -translateY / downScaleFactor);
c.scale(1f / downScaleFactor, 1f / downScaleFactor);
view.draw(c);
if (overlayColor != Color.TRANSPARENT) {
Paint paint = new Paint();
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
paint.setColor(overlayColor);
c.drawPaint(paint);
}
return dest;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public static void animateAlpha(@NonNull View view, float fromAlpha, float toAlpha, int duration,
@NonNull final Runnable endAction) {
if (IS_POST_HONEYCOMB_MR1) {
ViewPropertyAnimator animator = view.animate().alpha(toAlpha).setDuration(duration);
if (endAction != null) {
animator.setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
endAction.run();
}
});
}
} else {
AlphaAnimation alphaAnimation = new AlphaAnimation(fromAlpha, toAlpha);
alphaAnimation.setDuration(duration);
alphaAnimation.setFillAfter(true);
if (endAction != null) {
alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
// fixes the crash bug while removing views
Handler handler = new Handler(Looper.getMainLooper());
handler.post(endAction);
}
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationRepeat(Animation animation) { }
});
}
view.startAnimation(alphaAnimation);
}
}
} | 39.206186 | 126 | 0.626085 |
cd1af2df6e32148e6ac057e80e14cd8a2fb108bc | 44,853 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.editors;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.core.preference.IPreferenceChangeListener;
import org.eclipse.birt.core.preference.IPreferences;
import org.eclipse.birt.core.preference.PreferenceChangeEvent;
import org.eclipse.birt.report.designer.core.mediator.IMediatorColleague;
import org.eclipse.birt.report.designer.core.mediator.IMediatorRequest;
import org.eclipse.birt.report.designer.core.mediator.MediatorManager;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.core.model.views.outline.ScriptObjectNode;
import org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest;
import org.eclipse.birt.report.designer.internal.ui.editors.FileReportProvider;
import org.eclipse.birt.report.designer.internal.ui.editors.IAdvanceReportEditorPage;
import org.eclipse.birt.report.designer.internal.ui.editors.IRelatedFileChangeResolve;
import org.eclipse.birt.report.designer.internal.ui.editors.IReportEditor;
import org.eclipse.birt.report.designer.internal.ui.editors.LibraryProvider;
import org.eclipse.birt.report.designer.internal.ui.editors.parts.GraphicalEditorWithFlyoutPalette;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.ReportMultiBookPage;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.ReportMultiBookPage.EmptyPage;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.IResourceEditPart;
import org.eclipse.birt.report.designer.internal.ui.extension.EditorContributorManager;
import org.eclipse.birt.report.designer.internal.ui.extension.FormPageDef;
import org.eclipse.birt.report.designer.internal.ui.util.Policy;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.internal.ui.views.ILibraryProvider;
import org.eclipse.birt.report.designer.internal.ui.views.actions.GlobalActionFactory;
import org.eclipse.birt.report.designer.internal.ui.views.data.DataViewTreeViewerPage;
import org.eclipse.birt.report.designer.internal.ui.views.outline.DesignerOutlinePage;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.birt.report.designer.ui.preferences.PreferenceFactory;
import org.eclipse.birt.report.designer.ui.views.ElementAdapterManager;
import org.eclipse.birt.report.designer.ui.views.IReportResourceChangeEvent;
import org.eclipse.birt.report.designer.ui.views.IReportResourceChangeListener;
import org.eclipse.birt.report.designer.ui.views.IReportResourceSynchronizer;
import org.eclipse.birt.report.designer.ui.views.attributes.IAttributeViewPage;
import org.eclipse.birt.report.designer.ui.views.data.IDataViewPage;
import org.eclipse.birt.report.designer.ui.widget.ITreeViewerBackup;
import org.eclipse.birt.report.designer.ui.widget.TreeViewerBackup;
import org.eclipse.birt.report.model.api.IVersionInfo;
import org.eclipse.birt.report.model.api.MasterPageHandle;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.ModuleUtil;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.ui.views.palette.PalettePage;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IKeyBindingService;
import org.eclipse.ui.INestableKeyBindingService;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWindowListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartConstants;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.editor.IFormPage;
import org.eclipse.ui.part.IPageBookViewPage;
import org.eclipse.ui.part.MultiPageSelectionProvider;
import org.eclipse.ui.part.PageBookView;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
/**
*
* Base multipage editor for report editors. Clients can subclass this class to
* create customize report editors. Report editor pages can contributed through
* Extendtion Point
* org.eclipse.birt.report.designer.ui.editors.multiPageEditorContributor.
*
* @see IReportEditorPage
*/
public class MultiPageReportEditor extends AbstractMultiPageEditor implements
IPartListener,
IReportEditor,
IMediatorColleague,
IReportResourceChangeListener
{
public static final String LayoutMasterPage_ID = "org.eclipse.birt.report.designer.ui.editors.masterpage"; //$NON-NLS-1$
public static final String LayoutEditor_ID = "org.eclipse.birt.report.designer.ui.editors.layout"; //$NON-NLS-1$
public static final String XMLSourcePage_ID = "org.eclipse.birt.report.designer.ui.editors.xmlsource"; //$NON-NLS-1$
public static final String ScriptForm_ID = "org.eclipse.birt.report.designer.ui.editors.script"; //$NON-NLS-1$
public static int PROP_SAVE = 1000;
private ReportMultiBookPage fPalettePage;
private ReportMultiBookPage outlinePage;
private ReportMultiBookPage dataPage;
private boolean fIsHandlingActivation;
private long fModificationStamp = -1;;
protected IReportProvider reportProvider;
private FormEditorSelectionProvider provider = new FormEditorSelectionProvider( this );
private boolean isChanging = false;
private ReportMultiBookPage attributePage;
private ITreeViewerBackup outlineBackup;
private ITreeViewerBackup dataBackup;
private boolean needReload = false;
private boolean needReset = false;
private IWorkbenchPart fActivePart;
private boolean isClose = false;
// private IRelatedFileChangeResolve resolve;
private List<IRelatedFileChangeResolve> resolveList = new ArrayList<IRelatedFileChangeResolve>( );
private IPreferences prefs;
IPreferenceChangeListener preferenceChangeListener = new IPreferenceChangeListener( ) {
public void preferenceChange( PreferenceChangeEvent event )
{
if ( event.getKey( )
.equals( PreferenceChangeEvent.SPECIALTODEFAULT )
|| ReportPlugin.RESOURCE_PREFERENCE.equals( event.getKey( ) ) )
{
SessionHandleAdapter.getInstance( )
.getSessionHandle( )
.setBirtResourcePath( ReportPlugin.getDefault( )
.getResourcePreference( ) );
UIUtil.processSessionResourceFolder( getEditorInput( ),
UIUtil.getProjectFromInput( getEditorInput( ) ),
getModel( ) );
refreshGraphicalEditor( );
}
}
};
private IWindowListener windowListener = new IWindowListener( ) {
public void windowActivated( IWorkbenchWindow window )
{
if ( !( window == getEditorSite( ).getWorkbenchWindow( ) ) )
{
return;
}
if ( fActivePart != MultiPageReportEditor.this )
{
return;
}
window.getShell( ).getDisplay( ).asyncExec( new Runnable( ) {
public void run( )
{
confirmSave( );
}
} );
}
public void windowClosed( IWorkbenchWindow window )
{
}
public void windowDeactivated( IWorkbenchWindow window )
{
}
public void windowOpened( IWorkbenchWindow window )
{
}
};
protected void confirmSave( )
{
if ( fIsHandlingActivation )
return;
if ( !isExistModelFile( ) && !isClose )
{
// Thread.dumpStack( );
fIsHandlingActivation = true;
MessageDialog dialog = new MessageDialog( UIUtil.getDefaultShell( ),
Messages.getString( "MultiPageReportEditor.ConfirmTitle" ), //$NON-NLS-1$
null,
Messages.getString( "MultiPageReportEditor.SaveConfirmMessage" ), //$NON-NLS-1$
MessageDialog.QUESTION,
new String[]{
Messages.getString( "MultiPageReportEditor.SaveButton" ), Messages.getString( "MultiPageReportEditor.CloseButton" )}, 0 ); //$NON-NLS-1$ //$NON-NLS-2$
try
{
if ( dialog.open( ) == 0 )
{
doSave( null );
isClose = false;
}
else
{
Display display = getSite( ).getShell( ).getDisplay( );
display.asyncExec( new Runnable( ) {
public void run( )
{
closeEditor( false );
}
} );
isClose = true;
}
}
finally
{
fIsHandlingActivation = false;
needReset = false;
needReload = false;
}
}
}
// this is a bug because the getActiveEditor() return null, we should change
// the getActivePage()
// return the correct current page index.we may delete this class
// TODO
private static class FormEditorSelectionProvider extends
MultiPageSelectionProvider
{
private ISelection globalSelection;
/**
* @param multiPageEditor
*/
public FormEditorSelectionProvider( FormEditor formEditor )
{
super( formEditor );
}
public ISelection getSelection( )
{
IEditorPart activeEditor = ( (FormEditor) getMultiPageEditor( ) ).getActivePageInstance( );
// IEditorPart activeEditor = getActivePageInstance( );
if ( activeEditor != null )
{
ISelectionProvider selectionProvider = activeEditor.getSite( )
.getSelectionProvider( );
if ( selectionProvider != null )
return selectionProvider.getSelection( );
}
return globalSelection;
}
/*
* (non-Javadoc) Method declared on <code> ISelectionProvider </code> .
*/
public void setSelection( ISelection selection )
{
IEditorPart activeEditor = ( (FormEditor) getMultiPageEditor( ) ).getActivePageInstance( );
if ( activeEditor != null )
{
ISelectionProvider selectionProvider = activeEditor.getSite( )
.getSelectionProvider( );
if ( selectionProvider != null )
selectionProvider.setSelection( selection );
}
else
{
this.globalSelection = selection;
fireSelectionChanged( new SelectionChangedEvent( this,
globalSelection ) );
}
}
}
/**
* Constructor
*/
public MultiPageReportEditor( )
{
super( );
outlineBackup = new TreeViewerBackup( );
dataBackup = new TreeViewerBackup( );
IReportResourceSynchronizer synchronizer = ReportPlugin.getDefault( )
.getResourceSynchronizerService( );
if ( synchronizer != null )
{
synchronizer.addListener( IReportResourceChangeEvent.LibraySaveChange
| IReportResourceChangeEvent.ImageResourceChange
| IReportResourceChangeEvent.DataDesignSaveChange,
this );
}
PlatformUI.getWorkbench( ).addWindowListener( windowListener );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.forms.editor.FormEditor#init(org.eclipse.ui.IEditorSite,
* org.eclipse.ui.IEditorInput)
*/
public void init( IEditorSite site, IEditorInput input )
throws PartInitException
{
super.init( site, input );
// getSite( ).getWorkbenchWindow( )
// .getPartService( )
// .addPartListener( this );
site.setSelectionProvider( provider );
IReportProvider provider = getProvider( );
if ( provider != null && provider.getInputPath( input ) != null )
{
setPartName( provider.getInputPath( input ).lastSegment( ) );
firePropertyChange( IWorkbenchPartConstants.PROP_PART_NAME );
}
else
{
setPartName( input.getName( ) );
firePropertyChange( IWorkbenchPartConstants.PROP_PART_NAME );
}
// suport the mediator
MediatorManager.addGlobalColleague( this );
IProject project = UIUtil.getProjectFromInput( input );
prefs = PreferenceFactory.getInstance( )
.getPreferences( ReportPlugin.getDefault( ), project );
prefs.addPreferenceChangeListener( preferenceChangeListener );
}
protected IReportProvider getProvider( )
{
if ( reportProvider == null )
{
reportProvider = new FileReportProvider( );
}
return reportProvider;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.forms.editor.FormEditor#addPages()
*/
protected void addPages( )
{
List formPageList = EditorContributorManager.getInstance( )
.getEditorContributor( getEditorSite( ).getId( ) ).formPageList;
boolean error = false;
// For back compatible only.
// Provide warning message to let user select if the auto convert needs
// See bugzilla bug 136536 for detail.
String fileName = getProvider( ).getInputPath( getEditorInput( ) )
.toOSString( );
List message = ModuleUtil.checkVersion( fileName );
if ( message.size( ) > 0 )
{
IVersionInfo info = (IVersionInfo) message.get( 0 );
if ( !MessageDialog.openConfirm( UIUtil.getDefaultShell( ),
Messages.getString( "MultiPageReportEditor.CheckVersion.Dialog.Title" ), //$NON-NLS-1$
info.getLocalizedMessage( ) ) )
{
for ( Iterator iter = formPageList.iterator( ); iter.hasNext( ); )
{
FormPageDef pagedef = (FormPageDef) iter.next( );
if ( XMLSourcePage_ID.equals( pagedef.id ) )
{
try
{
addPage( pagedef.createPage( ), pagedef.displayName );
break;
}
catch ( Exception e )
{
}
}
}
return;
}
}
UIUtil.processSessionResourceFolder( getEditorInput( ),
UIUtil.getProjectFromInput( getEditorInput( ) ),
null );
// load the model first here, so consequent pages can directly use it
// without reloading
getProvider( ).getReportModuleHandle( getEditorInput( ) );
for ( Iterator iter = formPageList.iterator( ); iter.hasNext( ); )
{
FormPageDef pagedef = (FormPageDef) iter.next( );
try
{
addPage( pagedef.createPage( ), pagedef.displayName );
}
catch ( Exception e )
{
error = true;
}
}
if ( error )
{
setActivePage( XMLSourcePage_ID );
}
}
/**
* Add a IReportEditorPage to multipage editor.
*
* @param page
* @param title
* @return
* @throws PartInitException
*/
public int addPage( IReportEditorPage page, String title )
throws PartInitException
{
int index = super.addPage( page );
if ( title != null )
{
setPageText( index, title );
}
try
{
page.initialize( this );
page.init( createSite( page ), getEditorInput( ) );
}
catch ( Exception e )
{
// removePage( index );
throw new PartInitException( e.getMessage( ) );
}
return index;
}
/**
* Remove report editor page.
*
* @param id
* the page id.
*/
public void removePage( String id )
{
IFormPage page = findPage( id );
if ( page != null )
{
removePage( page.getIndex( ) );
}
}
/**
* Remove all report editor page.
*/
public void removeAllPages( )
{
for ( int i = pages.toArray( ).length - 1; i >= 0; i-- )
{
if ( pages.get( i ) != null )
this.removePage( ( (IFormPage) pages.get( i ) ).getId( ) );
}
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.ui.part.EditorPart#doSave(org.eclipse.core.runtime.
* IProgressMonitor)
*/
public void doSave( IProgressMonitor monitor )
{
boolean isReselect = false;
if ( getModel( ) != null
&& ModuleUtil.compareReportVersion( ModuleUtil.getReportVersion( ),
getModel( ).getVersion( ) ) > 0 )
{
if ( !MessageDialog.openConfirm( UIUtil.getDefaultShell( ),
Messages.getString( "MultiPageReportEditor.ConfirmVersion.Dialog.Title" ), Messages.getString( "MultiPageReportEditor.ConfirmVersion.Dialog.Message" ) ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
return;
}
else
{
isReselect = true;
}
}
getCurrentPageInstance( ).doSave( monitor );
fireDesignFileChangeEvent( );
if ( isReselect )
{
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
if ( getActivePageInstance( ) instanceof GraphicalEditorWithFlyoutPalette )
{
if ( ( (GraphicalEditorWithFlyoutPalette) getActivePageInstance( ) ).getGraphicalViewer( ) != null )
{
GraphicalEditorWithFlyoutPalette editor = (GraphicalEditorWithFlyoutPalette) getActivePageInstance( );
GraphicalViewer view = editor.getGraphicalViewer( );
UIUtil.resetViewSelection( view, true );
}
}
}
} );
}
}
private void fireDesignFileChangeEvent( )
{
UIUtil.doFinishSave( getModel( ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#doSaveAs()
*/
public void doSaveAs( )
{
getActivePageInstance( ).doSaveAs( );
setInput( getActivePageInstance( ).getEditorInput( ) );
// update site name
IReportProvider provider = getProvider( );
if ( provider != null )
{
setPartName( provider.getInputPath( getEditorInput( ) )
.lastSegment( ) );
firePropertyChange( IWorkbenchPartConstants.PROP_PART_NAME );
getProvider( ).getReportModuleHandle( getEditorInput( ) )
.setFileName( getProvider( ).getInputPath( getEditorInput( ) )
.toOSString( ) );
}
updateRelatedViews( );
fireDesignFileChangeEvent( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#isSaveAsAllowed()
*/
public boolean isSaveAsAllowed( )
{
if ( getActivePageInstance( ) != null )
{
return getActivePageInstance( ).isSaveAsAllowed( );
}
return false;
}
// /*
// * (non-Javadoc)
// *
// * @see org.eclipse.ui.forms.editor.FormEditor#isDirty()
// */
// public boolean isDirty( )
// {
// fLastDirtyState = computeDirtyState( );
// return fLastDirtyState;
// }
//
// private boolean computeDirtyState( )
// {
// IFormPage page = getActivePageInstance( );
// if ( page != null && page.isDirty( ) )
// return true;
// return false;
// }
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#getAdapter(java.lang.Class)
*/
public Object getAdapter( Class type )
{
if ( type == IReportProvider.class )
{
if ( reportProvider == null )
{
reportProvider = new FileReportProvider( );
}
return reportProvider;
}
else if ( type == ILibraryProvider.class )
{
return new LibraryProvider( );
}
else if ( type == PalettePage.class )
{
Object adapter = getPalettePage( );
updatePaletteView( getActivePageInstance( ) );
return adapter;
}
else if ( type == IContentOutlinePage.class )
{
/*
* Update the logic under eclipse 3.7, eclipse always call the
* getAdapter(OutlinePage) when handle the ShellActive event. So we
* don't need to call updateOutLineView every time, only call it
* when new a outline page.
*/
boolean update = outlinePage == null || outlinePage.isDisposed( );
Object adapter = getOutlinePage( );
if ( update )
{
updateOutLineView( getActivePageInstance( ) );
}
return adapter;
}
else if ( type == IDataViewPage.class )
{
Object adapter = getDataPage( );
updateDateView( getActivePageInstance( ) );
return adapter;
}
else if ( type == IAttributeViewPage.class )
{
Object adapter = getAttributePage( );
updateAttributeView( getActivePageInstance( ) );
return adapter;
}
else if ( getActivePageInstance( ) != null )
{
return getActivePageInstance( ).getAdapter( type );
}
return super.getAdapter( type );
}
private void updateAttributeView( IFormPage activePageInstance )
{
if ( attributePage == null )
{
return;
}
Object adapter = activePageInstance.getAdapter( IAttributeViewPage.class );
attributePage.setActivePage( (IPageBookViewPage) adapter );
}
private void updateDateView( IFormPage activePageInstance )
{
if ( dataPage == null )
{
return;
}
Object adapter = activePageInstance.getAdapter( IDataViewPage.class );
if ( adapter instanceof DataViewTreeViewerPage )
{
( (DataViewTreeViewerPage) adapter ).setBackupState( dataBackup );
}
dataPage.setActivePage( (IPageBookViewPage) adapter );
}
private void updateOutLineView( IFormPage activePageInstance )
{
if ( outlinePage == null )
{
return;
}
if ( reloadOutlinePage( ) )
{
return;
}
Object designOutLinePage = activePageInstance.getAdapter( IContentOutlinePage.class );
if ( designOutLinePage instanceof DesignerOutlinePage )
{
( (DesignerOutlinePage) designOutLinePage ).setBackupState( outlineBackup );
}
outlinePage.setActivePage( (IPageBookViewPage) designOutLinePage );
}
public void outlineSwitch( )
{
if ( !getActivePageInstance( ).getId( ).equals( XMLSourcePage_ID )
|| outlinePage == null )
{
return;
}
if ( outlinePage.getCurrentPage( ) instanceof DesignerOutlinePage )
{
outlinePage.setActivePage( (IPageBookViewPage) getActivePageInstance( ).getAdapter( ContentOutlinePage.class ) );
}
else
{
outlinePage.setActivePage( (IPageBookViewPage) getActivePageInstance( ).getAdapter( IContentOutlinePage.class ) );
}
outlinePage.getSite( ).getActionBars( ).updateActionBars( );
}
public boolean reloadOutlinePage( )
{
if ( !getActivePageInstance( ).getId( ).equals( XMLSourcePage_ID )
|| outlinePage == null
|| !getCurrentPageInstance( ).getId( )
.equals( XMLSourcePage_ID ) )
{
return false;
}
if ( outlinePage.getCurrentPage( ) instanceof DesignerOutlinePage
|| outlinePage.getCurrentPage( ) == null
|| outlinePage.getCurrentPage( ) instanceof EmptyPage )
{
outlinePage.setActivePage( (IPageBookViewPage) getActivePageInstance( ).getAdapter( IContentOutlinePage.class ) );
}
else
{
outlinePage.setActivePage( (IPageBookViewPage) getActivePageInstance( ).getAdapter( ContentOutlinePage.class ) );
}
if ( outlinePage.getSite( ) != null )
{
outlinePage.getSite( ).getActionBars( ).updateActionBars( );
}
return true;
}
private Object getDataPage( )
{
if ( dataPage == null || dataPage.isDisposed( ) )
{
dataPage = new ReportMultiBookPage( );
}
return dataPage;
}
private Object getAttributePage( )
{
if ( attributePage == null || attributePage.isDisposed( ) )
{
attributePage = new ReportMultiBookPage( );
}
return attributePage;
}
/**
* If new a outline page, should call updateOutLineView(
* getActivePageInstance( ) ) method at first.
*
* @Since 3.7.2
*
*/
public Object getOutlinePage( )
{
if ( outlinePage == null || outlinePage.isDisposed( ) )
{
outlinePage = new ReportMultiBookPage( );
}
return outlinePage;
}
private Object getPalettePage( )
{
if ( fPalettePage == null || fPalettePage.isDisposed( ) )
{
fPalettePage = new ReportMultiBookPage( );
}
return fPalettePage;
}
private void updatePaletteView( IFormPage activePageInstance )
{
if ( fPalettePage == null )
{
return;
}
Object palette = activePageInstance.getAdapter( PalettePage.class );
fPalettePage.setActivePage( (IPageBookViewPage) palette );
}
public void pageChange( String id )
{
IFormPage page = findPage( id );
if ( page != null )
{
pageChange( page.getIndex( ) );
}
}
protected void pageChange( int newPageIndex )
{
int oldPageIndex = getCurrentPage( );
if ( oldPageIndex == newPageIndex )
{
isChanging = false;
bingdingKey( oldPageIndex );
return;
}
if ( oldPageIndex != -1 )
{
Object oldPage = pages.get( oldPageIndex );
Object newPage = pages.get( newPageIndex );
if ( oldPage instanceof IFormPage )
{
if ( !( (IFormPage) oldPage ).canLeaveThePage( ) )
{
setActivePage( oldPageIndex );
return;
}
}
// change to new page, must do it first, because must check old page
// is canleave.
isChanging = true;
super.pageChange( newPageIndex );
// updateRelatedViews( );
// check new page status
if ( !prePageChanges( oldPage, newPage ) )
{
super.setActivePage( oldPageIndex );
updateRelatedViews( );
return;
}
else if ( isChanging )
{
bingdingKey( newPageIndex );
}
isChanging = false;
}
else
{
super.pageChange( newPageIndex );
}
updateRelatedViews( );
updateAttributeView( getActivePageInstance( ) );
}
public void setFocus( )
{
if ( getActivePageInstance( ) != null
&& getActivePageInstance( ).getPartControl( ) != null
&& UIUtil.containsFocusControl( getActivePageInstance( ).getPartControl( ) ) )
return;
super.setFocus( );
if ( pages == null
|| getCurrentPage( ) < 0
|| getCurrentPage( ) > pages.size( ) - 1 )
{
return;
}
bingdingKey( getCurrentPage( ) );
}
// this is a bug because the getActiveEditor() return null, we should change
// the getActivePage()
// return the correct current page index.we may delete this method
// TODO
private void bingdingKey( int newPageIndex )
{
final IKeyBindingService service = getSite( ).getKeyBindingService( );
final IEditorPart editor = (IEditorPart) pages.get( newPageIndex );
if ( editor != null && editor.getEditorSite( ) != null )
{
editor.setFocus( );
// There is no selected page, so deactivate the active service.
if ( service instanceof INestableKeyBindingService )
{
final INestableKeyBindingService nestableService = (INestableKeyBindingService) service;
if ( editor != null )
{
nestableService.activateKeyBindingService( editor.getEditorSite( ) );
}
else
{
nestableService.activateKeyBindingService( null );
}
}
else
{
}
}
}
public void updateRelatedViews( )
{
updatePaletteView( getCurrentPageInstance( ) );
updateOutLineView( getCurrentPageInstance( ) );
updateDateView( getCurrentPageInstance( ) );
}
protected boolean prePageChanges( Object oldPage, Object newPage )
{
boolean isNewPageValid = true;
if ( oldPage instanceof IReportEditorPage
&& newPage instanceof IReportEditorPage )
{
isNewPageValid = ( (IReportEditorPage) newPage ).onBroughtToTop( (IReportEditorPage) oldPage );
// TODO: HOW TO RESET MODEL?????????
// model = SessionHandleAdapter.getInstance(
// ).getReportDesignHandle( );
}
return isNewPageValid;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.forms.editor.FormEditor#editorDirtyStateChanged()
*/
public void editorDirtyStateChanged( )
{
super.editorDirtyStateChanged( );
markPageStale( );
}
private void markPageStale( )
{
// int currentIndex = getCurrentPage( );
IFormPage currentPage = getActivePageInstance( );
if ( !( currentPage instanceof IReportEditorPage ) )
{
return;
}
// if ( currentIndex != -1 )
// {
// for ( int i = 0; i < pages.size( ); i++ )
// {
// if ( i == currentIndex )
// {
// continue;
// }
// Object page = pages.get( i );
// if ( page instanceof IReportEditorPage )
// {
// ( (IReportEditorPage) page ).markPageStale( ( (IReportEditorPage)
// currentPage ).getStaleType( ) );
// }
// }
// }
}
/**
* Get the current report ModuleHandle.
*
* @return
*/
public ModuleHandle getModel( )
{
if ( reportProvider != null )
{
return reportProvider.queryReportModuleHandle( );
}
return null;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IPartListener#partActivated(org.eclipse.ui.IWorkbenchPart)
*/
public void partActivated( IWorkbenchPart part )
{
fActivePart = part;
if ( part != this )
{
if ( part instanceof PageBookView )
{
PageBookView view = (PageBookView) part;
if ( view.getCurrentPage( ) instanceof DesignerOutlinePage )
{
ISelectionProvider provider = (ISelectionProvider) view.getCurrentPage( );
ReportRequest request = new ReportRequest( view.getCurrentPage( ) );
List list = new ArrayList( );
if ( provider.getSelection( ) instanceof IStructuredSelection )
{
list = ( (IStructuredSelection) provider.getSelection( ) ).toList( );
}
request.setSelectionObject( list );
request.setType( ReportRequest.SELECTION );
// no convert
// request.setRequestConvert(new
// EditorReportRequestConvert());
SessionHandleAdapter.getInstance( )
.getMediator( )
.notifyRequest( request );
SessionHandleAdapter.getInstance( )
.getMediator( )
.pushState( );
}
}
if ( getActivePageInstance( ) instanceof GraphicalEditorWithFlyoutPalette )
{
if ( ( (GraphicalEditorWithFlyoutPalette) getActivePageInstance( ) ).getGraphicalViewer( )
.getEditDomain( )
.getPaletteViewer( ) != null )
{
GraphicalEditorWithFlyoutPalette editor = (GraphicalEditorWithFlyoutPalette) getActivePageInstance( );
GraphicalViewer view = editor.getGraphicalViewer( );
view.getEditDomain( ).loadDefaultTool( );
}
}
return;
}
if ( part == this )
{
confirmSave( );
final ModuleHandle oldHandle = getModel( );
if ( needReset )
{
if ( resolveList != null && resetList( resolveList ) )
{
getProvider( ).getReportModuleHandle( getEditorInput( ),
true );
}
else
{
needReset = false;
}
needReload = false;
}
if ( needReload )
{
if ( resolveList != null && reloadList( resolveList ) )
{
// do nothing now
}
else
{
needReload = false;
}
}
if ( getEditorInput( ).exists( ) )
{
handleActivation( );
ModuleHandle currentModel = getModel( );
SessionHandleAdapter.getInstance( )
.setReportDesignHandle( currentModel );
String str = SessionHandleAdapter.getInstance( )
.getSessionHandle( )
.getResourceFolder( );
UIUtil.processSessionResourceFolder( getEditorInput( ),
UIUtil.getProjectFromInput( getEditorInput( ) ),
currentModel );
if ( !str.equals( SessionHandleAdapter.getInstance( )
.getSessionHandle( )
.getResourceFolder( ) )
&& getActivePageInstance( ) instanceof GraphicalEditorWithFlyoutPalette )
{
( (GraphicalEditorWithFlyoutPalette) getActivePageInstance( ) ).getGraphicalViewer( )
.getRootEditPart( );
refreshGraphicalEditor( );
}
}
if ( // getActivePageInstance( ) instanceof
// GraphicalEditorWithFlyoutPalette
// &&
getActivePageInstance( ) instanceof IReportEditorPage )
{
boolean isDispatch = false;
if ( getActivePageInstance( ) instanceof GraphicalEditorWithFlyoutPalette )
{
isDispatch = true;
}
else if ( needReload || needReset )
{
isDispatch = true;
}
final boolean tempDispatch = isDispatch;
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
IReportEditorPage curPage = (IReportEditorPage) getActivePageInstance( );
if ( needReload || needReset )
{
curPage.markPageStale( IPageStaleType.MODEL_RELOAD );
}
if ( getActivePageInstance( ) != null )
{
if ( curPage instanceof IAdvanceReportEditorPage )
{
if ( ( (IAdvanceReportEditorPage) curPage ).isSensitivePartChange( ) )
{
curPage.onBroughtToTop( (IReportEditorPage) getActivePageInstance( ) );
}
}
else
{
curPage.onBroughtToTop( (IReportEditorPage) getActivePageInstance( ) );
}
}
if ( !tempDispatch )
{
return;
}
// UIUtil.resetViewSelection( view, true );
if ( needReload || needReset )
{
updateRelatedViews( );
// doSave( null );
UIUtil.refreshCurrentEditorMarkers( );
curPage.markPageStale( IPageStaleType.NONE );
}
if ( needReset )
{
SessionHandleAdapter.getInstance( )
.resetReportDesign( oldHandle, getModel( ) );
oldHandle.close( );
}
needReload = false;
needReset = false;
resolveList.clear( );
}
} );
// UIUtil.resetViewSelection( view, true );
}
}
// if ( getModel( ) != null )
// {
// getModel( ).setResourceFolder( getProjectFolder( ) );
// }
}
private boolean reloadList( List<IRelatedFileChangeResolve> list )
{
for ( int i = 0; i < list.size( ); i++ )
{
if ( !list.get( i ).reload( getModel( ) ) )
{
return false;
}
}
return true;
}
private boolean resetList( List<IRelatedFileChangeResolve> list )
{
for ( int i = 0; i < list.size( ); i++ )
{
if ( !list.get( i ).reset( ) )
{
return false;
}
}
return true;
}
private void refreshResourceEditPart( EditPart parent )
{
if ( parent instanceof IResourceEditPart )
{
( (IResourceEditPart) parent ).refreshResource( );
}
List list = parent.getChildren( );
for ( int i = 0; i < list.size( ); i++ )
{
EditPart part = (EditPart) list.get( i );
refreshResourceEditPart( part );
}
}
public boolean isExistModelFile( )
{
if ( getModel( ) == null )
{
return true;
}
File file = new File( getModel( ).getFileName( ) );
if ( file.exists( ) && file.isFile( ) )
{
return true;
}
return false;
}
// private String getProjectFolder( )
// {
// IEditorInput input = getEditorInput( );
// Object fileAdapter = input.getAdapter( IFile.class );
// IFile file = null;
// if ( fileAdapter != null )
// file = (IFile) fileAdapter;
// if ( file != null && file.getProject( ) != null )
// {
// return file.getProject( ).getLocation( ).toOSString( );
// }
// if ( input instanceof IPathEditorInput )
// {
// File fileSystemFile = ( (IPathEditorInput) input ).getPath( )
// .toFile( );
// return fileSystemFile.getParent( );
// }
// return null;
// }
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IPartListener#partBroughtToTop(org.eclipse.ui.IWorkbenchPart
* )
*/
public void partBroughtToTop( IWorkbenchPart part )
{
if ( part instanceof MultiPageReportEditor )
{
MultiPageReportEditor topEditor = (MultiPageReportEditor) part;
if ( topEditor.getModel( ) != null
&& topEditor.getModel( ) != SessionHandleAdapter.getInstance( )
.getModule( ) )
{
SessionHandleAdapter.getInstance( )
.setModule( topEditor.getModel( ) );
updateRelatedViews( );
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IPartListener#partClosed(org.eclipse.ui.IWorkbenchPart)
*/
public void partClosed( IWorkbenchPart part )
{
if ( part == this && getModel( ) != null )
{
SessionHandleAdapter.getInstance( ).clear( getModel( ) );
if ( getModel( ) != null )
{
GlobalActionFactory.removeStackActions( getModel( ).getCommandStack( ) );
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IPartListener#partDeactivated(org.eclipse.ui.IWorkbenchPart
* )
*/
public void partDeactivated( IWorkbenchPart part )
{
fActivePart = null;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IPartListener#partOpened(org.eclipse.ui.IWorkbenchPart)
*/
public void partOpened( IWorkbenchPart part )
{
}
/**
* Tell me, i am activated.
*
*/
public void handleActivation( )
{
// if ( fIsHandlingActivation )
// return;
//
// fIsHandlingActivation = true;
// try
// {
// // TODO: check external changes of file.
// // sanityCheckState( getEditorInput( ) );
// }
// finally
// {
// fIsHandlingActivation = false;
// }
}
/**
* check the input is modify by file system.
*
* @param input
*/
protected void sanityCheckState( IEditorInput input )
{
if ( fModificationStamp == -1 )
{
fModificationStamp = getModificationStamp( input );
}
long stamp = getModificationStamp( input );
if ( stamp != fModificationStamp )
{
// reset the stamp whether user choose sync or not to avoid endless
// snag window.
fModificationStamp = stamp;
handleEditorInputChanged( );
}
}
/**
* Handles an external change of the editor's input element. Subclasses may
* extend.
*/
protected void handleEditorInputChanged( )
{
String title = Messages.getString( "ReportEditor.error.activated.outofsync.title" ); //$NON-NLS-1$
String msg = Messages.getString( "ReportEditor.error.activated.outofsync.message" ); //$NON-NLS-1$
if ( MessageDialog.openQuestion( getSite( ).getShell( ), title, msg ) )
{
IEditorInput input = getEditorInput( );
if ( input == null )
{
closeEditor( isSaveOnCloseNeeded( ) );
}
else
{
// getInputContext( ).setInput( input );
// rebuildModel( );
// superSetInput( input );
}
}
}
public void closeEditor( boolean save )
{
getSite( ).getPage( ).closeEditor( this, save );
}
protected long getModificationStamp( Object element )
{
if ( element instanceof IEditorInput )
{
IReportProvider provider = getProvider( );
if ( provider != null )
{
return computeModificationStamp( provider.getInputPath( (IEditorInput) element ) );
}
}
return 0;
}
protected long computeModificationStamp( IPath path )
{
return path.toFile( ).lastModified( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.forms.editor.FormEditor#dispose()
*/
public void dispose( )
{
// dispose page
outlineBackup.dispose( );
dataBackup.dispose( );
List list = new ArrayList( pages );
int size = list.size( );
for ( int i = 0; i < size; i++ )
{
Object obj = list.get( i );
if ( obj instanceof IReportEditorPage )
{
( (IReportEditorPage) obj ).dispose( );
pages.remove( obj );
}
}
// getSite( ).getWorkbenchWindow( )
// .getPartService( )
// .removePartListener( this );
if ( fPalettePage != null )
{
fPalettePage.dispose( );
}
if ( outlinePage != null )
{
outlinePage.dispose( );
}
if ( dataPage != null )
{
dataPage.dispose( );
}
getSite( ).setSelectionProvider( null );
// remove the mediator listener
MediatorManager.removeGlobalColleague( this );
if ( getModel( ) != null )
{
getModel( ).close( );
}
IReportResourceSynchronizer synchronizer = ReportPlugin.getDefault( )
.getResourceSynchronizerService( );
if ( synchronizer != null )
{
synchronizer.removeListener( IReportResourceChangeEvent.LibraySaveChange
| IReportResourceChangeEvent.ImageResourceChange
| IReportResourceChangeEvent.DataDesignSaveChange,
this );
}
PlatformUI.getWorkbench( ).removeWindowListener( windowListener );
if ( prefs != null )
{
prefs.removePreferenceChangeListener( preferenceChangeListener );
}
super.dispose( );
}
protected void finalize( ) throws Throwable
{
if ( Policy.TRACING_PAGE_CLOSE )
{
System.out.println( "Report multi page finalized" ); //$NON-NLS-1$
}
super.finalize( );
}
public IEditorPart getEditorPart( )
{
return this;
}
public boolean isInterested( IMediatorRequest request )
{
return request instanceof ReportRequest;
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.designer.internal.ui.editors.parts.
* GraphicalEditorWithFlyoutPalette
* #performRequest(org.eclipse.birt.report.designer
* .core.util.mediator.request.ReportRequest)
*/
public void performRequest( IMediatorRequest request )
{
ReportRequest rqt = (ReportRequest) request;
if ( ReportRequest.OPEN_EDITOR.equals( request.getType( ) )
&& ( rqt.getSelectionModelList( ).size( ) == 1 ) )
{
if ( rqt.getSelectionModelList( ).get( 0 ) instanceof MasterPageHandle )
{
handleOpenMasterPage( rqt );
return;
}
if ( rqt.getSelectionModelList( ).get( 0 ) instanceof ScriptObjectNode )
{
ScriptObjectNode node = (ScriptObjectNode) rqt.getSelectionModelList( )
.get( 0 );
if ( node.getParent( ) instanceof PropertyHandle )
{
PropertyHandle proHandle = (PropertyHandle) node.getParent( );
if ( proHandle.getElementHandle( )
.getModuleHandle( )
.equals( getModel( ) ) )
{
handleOpenScriptPage( rqt );
}
}
// handleOpenScriptPage( request );
return;
}
}
// super.performRequest( request );
}
/**
* @param request
*/
protected void handleOpenScriptPage( final ReportRequest request )
{
if ( this.getContainer( ).isVisible( ) )
{
setActivePage( ScriptForm_ID );
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
ReportRequest r = new ReportRequest( );
r.setType( ReportRequest.SELECTION );
r.setSelectionObject( request.getSelectionModelList( ) );
SessionHandleAdapter.getInstance( )
.getMediator( )
.notifyRequest( r );
}
} );
}
}
/**
* @param request
*/
protected void handleOpenMasterPage( final ReportRequest request )
{
if ( this.getContainer( ).isVisible( ) )
{
setActivePage( LayoutMasterPage_ID );
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
ReportRequest r = new ReportRequest( );
r.setType( ReportRequest.LOAD_MASTERPAGE );
r.setSelectionObject( request.getSelectionModelList( ) );
SessionHandleAdapter.getInstance( )
.getMediator( )
.notifyRequest( r );
}
} );
}
}
/**
* Returns current page instance if the currently selected page index is not
* -1, or <code>null</code> if it is.
*
* @return active page instance if selected, or <code>null</code> if no page
* is currently active.
*/
public IFormPage getCurrentPageInstance( )
{
int index = getCurrentPage( );
if ( index != -1 )
{
Object page = pages.get( index );
if ( page instanceof IFormPage )
return (IFormPage) page;
}
return null;
}
private void refreshGraphicalEditor( )
{
for ( int i = 0; i < pages.size( ); i++ )
{
Object page = pages.get( i );
if ( page instanceof IFormPage )
{
if ( isGraphicalEditor( page ) )
{
if ( ( (GraphicalEditorWithFlyoutPalette) page ).getGraphicalViewer( ) != null )
{
EditPart root = ( (GraphicalEditorWithFlyoutPalette) page ).getGraphicalViewer( )
.getRootEditPart( );
refreshResourceEditPart( root );
}
}
}
}
}
private boolean isGraphicalEditor( Object obj )
{
return obj instanceof GraphicalEditorWithFlyoutPalette;
// return LayoutEditor_ID.equals( id ) || LayoutMasterPage_ID.equals( id
// );
}
protected void setActivePage( int pageIndex )
{
super.setActivePage( pageIndex );
// setFocus( );
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
setFocus( );
}
} );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.designer.ui.views.IReportResourceChangeListener
* #resourceChanged
* (org.eclipse.birt.report.designer.ui.views.IReportResourceChangeEvent)
*/
public void resourceChanged( IReportResourceChangeEvent event )
{
if ( ( event.getType( ) == IReportResourceChangeEvent.ImageResourceChange ) )
{
refreshGraphicalEditor( );
return;
}
if ( event.getSource( ).equals( getModel( ) ) )
{
return;
}
Object[] resolves = ElementAdapterManager.getAdapters( getModel( ),
IRelatedFileChangeResolve.class );
if ( resolves == null )
{
return;
}
Path targetPath=(Path)event.getData();
for ( int i = 0; i < resolves.length; i++ )
{
IRelatedFileChangeResolve find = (IRelatedFileChangeResolve) resolves[i];
if ( find.acceptType( event.getType( ) ) )
{
/**
* Check whether the resolveList already contains the same type of the new IRelatedFileChangeResolve.
* Add the new resolve to the resolveList only if the list doesn't contain objects have the same type of the new resolve.
* This judgment call tries to prevent duplicate refresh action when several resources change happens.
*/
if(!checkResolveListContainsType(find)){
if(targetPath!=null ){
if(targetPath.toOSString().equals(getModel( ).getFileName())){
addToResolveList(event,find);
}
}else{//if targetPath is null, follow the old logic
addToResolveList(event,find);
}
}
break;
}
}
}
private void addToResolveList(IReportResourceChangeEvent event,IRelatedFileChangeResolve find){
resolveList.add( find );
needReload = find.isReload( event, getModel( ) );
needReset = find.isReset( event, getModel( ) );
}
/**
* Check whether the resolveList already contains the same type of the new IRelatedFileChangeResolve.
* @param find
* @return
*/
private boolean checkResolveListContainsType(IRelatedFileChangeResolve find){
for(int i=0;i<resolveList.size();i++){
IRelatedFileChangeResolve obj=resolveList.get(i);
if(find.getClass().equals(obj.getClass())){
return true;
}
}
return false;
}
}
| 25.911612 | 187 | 0.679486 |
2fc191f4987ed46911de293b07fbf8cd991271d7 | 356 | package com.luneruniverse.minecraft.mod.nbteditor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.fabricmc.api.ModInitializer;
public class NBTEditor implements ModInitializer {
public static final Logger LOGGER = LogManager.getLogger("nbteditor");
@Override
public void onInitialize() {
}
}
| 19.777778 | 71 | 0.783708 |
df510a9e891b55e2c67fd2001c67f046bec4adba | 4,583 | //-----------------------------------------------------------------------
// Copyright 2011 Ciaran McHale.
//
// 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.
//----------------------------------------------------------------------
import org.config4j.Configuration;
import org.config4j.ConfigurationException;
import org.config4j.SchemaType;
import org.config4j.SchemaValidator;
public class SchemaTypeHex extends SchemaType
{
public SchemaTypeHex()
{
super("hex", Configuration.CFG_STRING);
}
public void checkRule(
SchemaValidator sv,
Configuration cfg,
String typeName,
String[] typeArgs,
String rule) throws ConfigurationException
{
int len;
int maxDigits;
len = typeArgs.length;
if (len == 0) {
return;
} else if (len > 1) {
throw new ConfigurationException("schema error: the '" + typeName
+ "' type should take either no arguments or 1 "
+ "argument (denoting max-digits) "
+ "in rule '" + rule + "'");
}
try {
maxDigits = cfg.stringToInt("", "", typeArgs[0]);
} catch(ConfigurationException ex) {
throw new ConfigurationException("schema error: non-integer value "
+ "for the 'max-digits' argument in rule '" + rule + "'");
}
if (maxDigits < 1) {
throw new ConfigurationException("schema error: the max-digits "
+ "argument must be 1 or greater in rule '" + rule + "'");
}
}
public boolean isA(
SchemaValidator sv,
Configuration cfg,
String value,
String typeName,
String[] typeArgs,
int indentLevel,
StringBuffer errSuffix) throws ConfigurationException
{
int maxDigits;
if (!isHex(value)) {
errSuffix.append("the value is not a hexadecimal number");
return false;
}
if (typeArgs.length == 1) {
//--------
// Check if there are too many hex digits in the value
//--------
maxDigits = cfg.stringToInt("", "", typeArgs[0]);
if (value.length() > maxDigits) {
errSuffix.append("the value must not contain more than "
+ maxDigits + " digits");
return false;
}
}
return true;
}
public static int lookupHex(
Configuration cfg,
String scope,
String localName) throws ConfigurationException
{
String str;
str = cfg.lookupString(scope, localName);
return stringToHex(cfg, scope, localName, str);
}
public static int lookupHex(
Configuration cfg,
String scope,
String localName,
int defaultVal) throws ConfigurationException
{
String str;
if (cfg.type(scope, localName) == Configuration.CFG_NO_VALUE) {
return defaultVal;
}
str = cfg.lookupString(scope, localName);
return stringToHex(cfg, scope, localName, str);
}
public static int stringToHex(
Configuration cfg,
String scope,
String localName,
String str) throws ConfigurationException
{
return stringToHex(cfg, scope, localName, str, "hex");
}
public static int stringToHex(
Configuration cfg,
String scope,
String localName,
String str,
String typeName) throws ConfigurationException
{
String fullyScopedName;
try {
return (int)Long.parseLong(str, 16);
} catch(NumberFormatException ex) {
fullyScopedName = cfg.mergeNames(scope, localName);
throw new ConfigurationException(cfg.fileName() + ": bad "
+ typeName + " value ('" + str + "') specified for '"
+ fullyScopedName);
}
}
public static boolean isHex(String str)
{
try {
Long.parseLong(str, 16);
return true;
} catch(NumberFormatException ex) {
return false;
}
}
}
| 26.80117 | 73 | 0.663103 |
813023075cb92ea242657c8773f35d32047fe517 | 989 | package me.kadary.microservices.blog.posts;
import org.springframework.data.annotation.Id;
public class Post {
@Id
private String postId;
private String userId;
private String title;
private String content;
public Post() {
}
public Post(String userId, String title, String content) {
this.setUserId(userId);
this.setTitle(title);
this.setContent(content);
}
public String getPostId() {
return postId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return String.format(
"Post[postId=%s, userId='%s', title='%s', content='%s']",
postId, userId, title, content);
}
}
| 14.984848 | 73 | 0.665319 |
321a4d56737dc6a1186ec84d047eca6245b7154f | 321 | package mb.tiger.intellij;
import mb.spoofax.intellij.IntellijFileElementType;
import mb.tiger.spoofax.TigerScope;
import javax.inject.Inject;
@TigerScope
public class TigerFileElementType extends IntellijFileElementType {
@Inject public TigerFileElementType() {
super(TigerPlugin.getComponent());
}
}
| 22.928571 | 67 | 0.785047 |
344f85420437781617cb87e3037d8c4a200149bc | 1,799 | /**
* 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.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*/
package org.thingml.compilers.javascript.browser;
import org.thingml.compilers.builder.Section;
import org.thingml.compilers.javascript.JSContext;
import org.thingml.compilers.javascript.JSSourceBuilder;
import org.thingml.compilers.javascript.JSSourceBuilder.JSClass;
import org.thingml.compilers.javascript.JSThingImplCompiler;
import org.thingml.xtext.thingML.Thing;
public class BrowserJSThingImplCompiler extends JSThingImplCompiler {
@Override
protected String getThingPath(Thing thing, JSContext jctx) {
return jctx.firstToUpper(thing.getName()) + ".js";
}
@Override
protected Section createMainSection(Thing thing, JSSourceBuilder builder, JSContext jctx) {
builder.append("'use strict';").append("");
Section main = builder.section("main").lines();
return main;
}
@Override
protected JSClass newThingClass(Thing thing, Section parent, JSContext jctx) {
return JSSourceBuilder.es5Class(parent, jctx.firstToUpper(thing.getName()));
}
@Override
protected void stop(StringBuilder builder) {
builder.append("setTimeout(()=>this._stop(),0);\n");
}
}
| 34.596154 | 92 | 0.753752 |
ac1a455a3cdffd9a025fec0ef8662ee4dd47fa10 | 4,660 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.analysis;
import org.apache.lucene.analysis.CharArraySet;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.test.ESTestCase;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.Matchers.is;
public class AnalysisTests extends ESTestCase {
public void testParseStemExclusion() {
/* Comma separated list */
Settings settings = Settings.builder().put("stem_exclusion", "foo,bar").build();
CharArraySet set = Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET);
assertThat(set.contains("foo"), is(true));
assertThat(set.contains("bar"), is(true));
assertThat(set.contains("baz"), is(false));
/* Array */
settings = Settings.builder().putList("stem_exclusion", "foo", "bar").build();
set = Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET);
assertThat(set.contains("foo"), is(true));
assertThat(set.contains("bar"), is(true));
assertThat(set.contains("baz"), is(false));
}
public void testParseNonExistingFile() {
Path tempDir = createTempDir();
Settings nodeSettings = Settings.builder()
.put("foo.bar_path", tempDir.resolve("foo.dict"))
.put(Environment.PATH_HOME_SETTING.getKey(), tempDir)
.build();
Environment env = TestEnvironment.newEnvironment(nodeSettings);
IllegalArgumentException ex = expectThrows(
IllegalArgumentException.class,
() -> Analysis.getWordList(env, nodeSettings, "foo.bar")
);
assertEquals("IOException while reading foo.bar_path: " + tempDir.resolve("foo.dict").toString(), ex.getMessage());
assertTrue(
ex.getCause().toString(),
ex.getCause() instanceof FileNotFoundException || ex.getCause() instanceof NoSuchFileException
);
}
public void testParseFalseEncodedFile() throws IOException {
Path tempDir = createTempDir();
Path dict = tempDir.resolve("foo.dict");
Settings nodeSettings = Settings.builder().put("foo.bar_path", dict).put(Environment.PATH_HOME_SETTING.getKey(), tempDir).build();
try (OutputStream writer = Files.newOutputStream(dict)) {
writer.write(new byte[] { (byte) 0xff, 0x00, 0x00 }); // some invalid UTF-8
writer.write('\n');
}
Environment env = TestEnvironment.newEnvironment(nodeSettings);
IllegalArgumentException ex = expectThrows(
IllegalArgumentException.class,
() -> Analysis.getWordList(env, nodeSettings, "foo.bar")
);
assertEquals(
"Unsupported character encoding detected while reading foo.bar_path: "
+ tempDir.resolve("foo.dict").toString()
+ " - files must be UTF-8 encoded",
ex.getMessage()
);
assertTrue(
ex.getCause().toString(),
ex.getCause() instanceof MalformedInputException || ex.getCause() instanceof CharacterCodingException
);
}
public void testParseWordList() throws IOException {
Path tempDir = createTempDir();
Path dict = tempDir.resolve("foo.dict");
Settings nodeSettings = Settings.builder().put("foo.bar_path", dict).put(Environment.PATH_HOME_SETTING.getKey(), tempDir).build();
try (BufferedWriter writer = Files.newBufferedWriter(dict, StandardCharsets.UTF_8)) {
writer.write("hello");
writer.write('\n');
writer.write("world");
writer.write('\n');
}
Environment env = TestEnvironment.newEnvironment(nodeSettings);
List<String> wordList = Analysis.getWordList(env, nodeSettings, "foo.bar");
assertEquals(Arrays.asList("hello", "world"), wordList);
}
}
| 43.551402 | 138 | 0.672532 |
24f4a4f718166d4ca9770dc9db16cf0ef4463b76 | 296 | package at.wrk.fmd.mls.amqp;
/**
* This class contains the names of replay related exchanges and headers
*/
public class ReplayConstants {
public static final String REPLAY_TRIGGER_EXCHANGE = "replay.trigger";
public static final String ROUTING_KEY_HEADER = "x-replay-routing-key";
}
| 26.909091 | 75 | 0.756757 |
88a40cc41b5766742eafc963b32ad6c695325cb0 | 999 | package main;
import org.junit.Before;
import edge.Edge;
import ghandler.GraphHandler;
import graph.Graph;
public class Main {
public static void main(String[] args) throws Exception {
/*GraphHandler gh = new GraphHandler();
Graph g = gh.readGraph("input.txt");
if (g != null) {
System.out.println(gh.getEdgeNumber(g));
}*/
Graph grafo;
Edge edge;
GraphHandler controller = new GraphHandler();
int vertices;
Integer[] ArrayO = new Integer[]{1, 2, 5, 4, 1};
Integer[] ArrayD = new Integer[]{2, 5, 3, 5, 5};
//grafotxt = new GraphHandler();
vertices = 5;
grafo = new Graph(vertices, false);
for(int i = 0; i < ArrayO.length; i++) {
String origem = String.valueOf(ArrayO[i]);
String destino = String.valueOf(ArrayD[i]);
edge = new Edge(origem, destino);
grafo.addEdge(edge);
}
System.out.println(controller.getEdgeNumber(grafo));
}
}
| 23.232558 | 61 | 0.591592 |
db80bdd5c6b48efee9f2bfcfdab60465d32592de | 600 | // Generated source
package org.jetbrains.wip.protocol.network;
/**
* This method sends a new XMLHttpRequest which is identical to the original one. The following parameters should be identical: method, url, async, request body, extra headers, withCredentials attribute, user, password.
*/
public final class ReplayXHR extends org.jetbrains.wip.protocol.WipRequest {
/**
* @param requestId Identifier of XHR to replay.
*/
public ReplayXHR(String requestId) {
writeString("requestId", requestId);
}
@Override
public String getMethodName() {
return "Network.replayXHR";
}
} | 33.333333 | 219 | 0.741667 |
bf0ae2d65528aae7bf1ce8d428c74890df3e4455 | 3,941 | /*
* (C) Copyright IBM Corp. 2016,2020
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.whc.deid.models;
import java.io.Serializable;
import java.security.SecureRandom;
/**
* Unicode compliant CharacterRange. This represents a range of characters and should be compliant
* with UTF-16, with built in support for Unicode if 2 byte points are used in the string.
*
* <p>
* Implements the TokenSet interface to be used when building strings.
*
*/
public class CharacterRange implements TokenSet, Serializable {
/**
*
*/
private static final long serialVersionUID = -7775741633828291049L;
// Start of the range
private Integer start = null;
// End of the range
private Integer end = null;
// Length of the range.
private int size;
/**
* Create a Character Range using the 2 integers. The range is omnidirectional; order does not
* matter.
*
* @param start An integer representing a unicode character
* @param end An integer representing a unicode character
*/
public CharacterRange(int start, int end) {
putToParameters(start, end);
}
/**
* Create a Character Range using the 2 chars. Since java chars are UTF16, the charset is limited
* to those code points. The range is omnidirectional; order does not matter.
*
* @param start A char representing a UTF16 character
* @param end An char representing a UTF character
*/
public CharacterRange(char start, char end) {
putToParameters(start, end);
}
/**
* A single character range
*
* @param character A single character in UTF16
*/
public CharacterRange(char character) {
putToParameters(character, character);
}
/**
* A single character range
*
* @param character A single integer code point in Unicode
*/
public CharacterRange(int character) {
putToParameters(character, character);
}
/**
* A single Unicode string-encoded character
*
* @param character A string containing a unicode character (2 byte characters supported)
*/
public CharacterRange(String character) {
putToParameters(character.codePointAt(0), character.codePointAt(0));
}
/**
* A range of Unicode characters represented between the first unicode point of the parameters.
* Two byte characters are supported. The range is omnidirectional; order does not matter.
*
* @param start A string containing a unicode character (2 byte characters supported)
* @param end A string containing a unicode character (2 byte characters supported)
*/
public CharacterRange(String start, String end) {
putToParameters(start.codePointAt(0), end.codePointAt(0));
}
@Override
public String getRandomToken(SecureRandom random) {
if (size == 1) {
return String.valueOf(Character.toChars(start));
}
int randomInt = random.nextInt(end - start);
return String.valueOf(Character.toChars(start + randomInt));
}
/**
* Put the start and end characters in to the instance vars, reversing the order if need be.
*
* @param start the starting Unicode character
* @param end the ending Unicode character
*/
private void putToParameters(int start, int end) {
if (start > end) {
int temp = start;
start = end;
end = temp;
}
this.end = end;
this.start = start;
this.size = end - start + 1;
}
@Override
public String getTokenAt(int index) {
return String.valueOf(Character.toChars(start + index));
}
@Override
public int getSize() {
return size;
}
public static final CharacterRange ENGLISH_DIGITS = new CharacterRange('0', '9');
public static final CharacterRange ENGLISH_LETTERS_CAPS = new CharacterRange('A', 'Z');
public static final CharacterRange ENGLISH_LETTERS_LOWER = new CharacterRange('a', 'z');
}
| 28.766423 | 100 | 0.673433 |
333a5397b5ec4e939f925cd7c07a7ac78d6591f2 | 3,598 | package no.nav.data.polly.informationtype.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Singular;
import lombok.experimental.FieldNameConstants;
import lombok.extern.slf4j.Slf4j;
import no.nav.data.common.validator.FieldValidator;
import no.nav.data.common.validator.RequestElement;
import no.nav.data.polly.codelist.domain.ListName;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import static no.nav.data.common.utils.StreamUtils.nullToEmptyList;
import static no.nav.data.common.utils.StreamUtils.safeStream;
import static no.nav.data.common.utils.StringUtils.formatList;
import static no.nav.data.common.utils.StringUtils.toUpperCaseAndTrim;
@Slf4j
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@FieldNameConstants
public class InformationTypeRequest implements RequestElement {
private String id;
private String name;
private String description;
private String term;
@Schema(description = "Codelist SENSITIVITY")
private String sensitivity;
@Schema(description = "Codelist SYSTEM")
private String orgMaster;
@Singular
private List<String> productTeams;
@Schema(description = "Codelist CATEGORY", example = "[\"CODELIST\"]")
private List<String> categories;
@Schema(description = "Codelist THIRD_PARTY", example = "[\"CODELIST\"]")
private List<String> sources;
private List<String> keywords;
private boolean update;
private int requestIndex;
@Override
public String getIdentifyingFields() {
return name;
}
@Override
public void format() {
setName(StringUtils.stripToNull(name));
setDescription(StringUtils.stripToNull(description));
setTerm(StringUtils.stripToNull(term));
setSensitivity(toUpperCaseAndTrim(getSensitivity()));
setOrgMaster(toUpperCaseAndTrim(getOrgMaster()));
setProductTeams(formatList(getProductTeams()));
setCategories(nullToEmptyList(categories).stream()
.map(StringUtils::stripToNull)
.map(String::toUpperCase)
.collect(Collectors.toList()));
setSources(nullToEmptyList(sources).stream()
.map(StringUtils::stripToNull)
.map(String::toUpperCase)
.collect(Collectors.toList()));
setKeywords(safeStream(keywords)
.map(StringUtils::stripToNull)
.filter(StringUtils::isNotBlank)
.collect(Collectors.toList()));
}
public static void initiateRequests(List<InformationTypeRequest> requests, boolean update) {
AtomicInteger requestIndex = new AtomicInteger(1);
requests.forEach(request -> {
request.setUpdate(update);
request.setRequestIndex(requestIndex.getAndIncrement());
});
}
@Override
public void validate(FieldValidator validator) {
validator.checkUUID(Fields.id, id);
validator.checkId(this);
validator.checkBlank(Fields.name, getName());
validator.checkCodelists(Fields.categories, getCategories(), ListName.CATEGORY);
validator.checkCodelists(Fields.sources, getSources(), ListName.THIRD_PARTY);
validator.checkRequiredCodelist(Fields.sensitivity, getSensitivity(), ListName.SENSITIVITY);
validator.checkCodelist(Fields.orgMaster, getOrgMaster(), ListName.SYSTEM);
}
}
| 35.98 | 100 | 0.715675 |
a84bb8194bb1b7afa2b7dfb6cb31adce06ef8e6c | 3,555 | package com.blogofbug.tests;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetChangeListener;
import org.jfree.data.general.DatasetGroup;
import de.fherfurt.imagecompare.swing.components.ImageComponent;
import de.fherfurt.imagecompare.util.ICUtil;
public class ChartTest extends JFrame {
private static final long serialVersionUID = 1L;
public ChartTest(ImageComponent ic) {
getContentPane().add(new MyChart(ic));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setSize(270, 250);
}
public static void main(String[] args) {
// new ChartTest();
}
}
class MyChart extends JComponent {
private static final long serialVersionUID = 1L;
ButtonGroup group;
JRadioButton rb;
JRadioButton gb;
JRadioButton bb;
JRadioButton lb;
ImageComponent ic;
public MyChart(ImageComponent ic) {
this.ic = ic;
setPreferredSize(new Dimension(256, 200));
setLayout(new FlowLayout());
group = new ButtonGroup();
rb = new JRadioButton("r");
gb = new JRadioButton("g");
bb = new JRadioButton("b");
lb = new JRadioButton("l", true);
group.add(rb);
group.add(gb);
group.add(bb);
group.add(lb);
rb.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if(((JRadioButton) e.getSource()).isSelected()) {
paint(getGraphics());
}
}});
gb.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if(((JRadioButton) e.getSource()).isSelected()) {
paint(getGraphics());
}
}});
bb.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if(((JRadioButton) e.getSource()).isSelected()) {
paint(getGraphics());
}
}});
lb.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if(((JRadioButton) e.getSource()).isSelected()) {
paint(getGraphics());
}
}});
add(rb);
add(gb);
add(bb);
add(lb);
}
@Override
public void paint(Graphics g) {
g.clearRect(1, 1, 255, 199);
int x = 0;
for(int i = 0; i < 255; i++) {
int val = 0;
if(rb.isSelected()) {
val = ic.getRed().get(i);
g.setColor(Color.black);
g.drawRect(x, 200-(val/100), 1, val/100);
g.setColor(new Color(i, 0, 0));
}
else if(gb.isSelected()) {
val = ic.getGreen().get(i);
g.setColor(Color.black);
g.drawRect(x, 200-(val/100), 1, val/100);
g.setColor(new Color(0, i, 0));
}
else if(bb.isSelected()) {
val = ic.getBlue().get(i);
g.setColor(Color.black);
g.drawRect(x, 200-(val/100), 1, val/100);
g.setColor(new Color(0, 0, i));
}
else {
val = ic.getLum().get(i);
g.setColor(Color.black);
g.drawRect(x, 200-(val/100), 1, val/100);
g.setColor(new Color(i, i, i));
}
g.fillRect(x, 200-(val/100), 1, val/100);
g.fillRect(x, 200, 1, 10);
x++;
}
g.setColor(Color.black);
g.drawRect(0, 200, 256, 10);
g.drawRect(0, 0, 256, 200);
super.paint(g);
}
} | 25.392857 | 65 | 0.638819 |
ba255b14b3bd947eb6c8218302e3eb955064a83e | 1,515 | package com.cspirat;
import java.util.HashMap;
/**
* Project Name : Leetcode
* Package Name : leetcode
* File Name : WordPattern
* Creator : Edward
* Date : Nov, 2017
* Description : 290. Word Pattern
*/
public class WordPattern {
/**
* Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
time : O(n) space : O(n)
* @param pattern
* @param str
* @return
*/
public boolean wordPattern(String pattern, String str) {
String[] arr = str.split(" ");
if (arr.length != pattern.length()) {
return false;
}
HashMap<Character, String> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
char c = pattern.charAt(i);
if (map.containsKey(c)) {
if (!map.get(c).equals(arr[i])) {
return false;
} else {
if (map.containsValue(arr[i])) {
return false;
}
map.put(c, arr[i]);
}
}
}
return true;
}
}
| 28.584906 | 124 | 0.535314 |
78e418d70b03fd37a44ed98d022dcd2b42f198af | 505 | /*
* Created by Itzik Braun on 12/3/2015.
* Copyright (c) 2015 deluge. All rights reserved.
*
* Last Modification at: 3/12/15 4:27 PM
*/
package com.braunster.chatsdk.interfaces;
/**
* Created by braunster on 30/06/14.
*/
public interface AppBatchedEvents {
public boolean onUsersBatchDetailsChange();
public boolean onMessagesBatchReceived();
public boolean onThreadsBatchIsAdded();
public boolean onThreadDetailsChanged();
public boolean onUsersBatchAddedToThread();
}
| 20.2 | 50 | 0.726733 |
2dc726ad4b9465d1027f458f018b3ed35c2486a7 | 11,893 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package servidor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
/**
*
* @author vitoria
*/
public class TratamentoClass implements Runnable {
private Socket cliente;
public TratamentoClass(Socket cliente) {
this.cliente = cliente;
}
@Override
public void run() {
Gerenciamento g = new Gerenciamento();
try {
InputStream is = cliente.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String dados = br.readLine();
String returnMessage = "";
if(dados.split(">")[0].equals("LOGIN")) {
System.out.println("Buscando pelo login!");
returnMessage = g.FazerLogin(dados.split(">")[1]);
System.out.println("Passou daqui");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println(returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("CadUser")) {
g.CadastrarUsuario(dados.split(">")[1]);
System.out.println("Cadastrando um novo usuário...");
} else if(dados.split(">")[0].equals("VerificarConta")) {
returnMessage = g.VerificarConta(dados.split(">")[1]);
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Conta verificada!");
bw.flush();
} else if(dados.split(">")[0].equals("CadEvento")) {
g.CadastrarEvento(dados.split(">")[1]);
System.out.println("Cadastrando um novo evento...");
} else if(dados.split(">")[0].equals("CadMinicurso")) {
returnMessage = g.CadastrarMinicurso(dados.split(">")[1]);
System.out.println("Cadastrando um novo minicurso...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("ReturnMessage:: " + returnMessage);
bw.flush();
} else if(dados.equals("BuscarEventos")) {
returnMessage = g.BuscarEventos();
System.out.println("Buscando os eventos disponíveis...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println(returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("BuscarInscritos")) {
returnMessage = g.BuscarInscritos(dados.split(">")[1]);
System.out.println("Buscando inscritos do evento " + dados.split(">")[1] + "...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println(returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("ExcluirEvento")) {
returnMessage = g.ExcluirEvento(dados.split(">")[1]);
System.out.println("Excluindo evento " + dados.split(">")[1] + "...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println(returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("EditarEvento")) {
returnMessage = g.EditarEvento(dados.split(">")[1]);
System.out.println("Editando evento " + dados.split(">")[1] + "...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println(returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("BuscarUmEvento")) {
returnMessage = g.BuscarUmEvento(dados.split(">")[1]);
System.out.println("Buscando evento " + dados.split(">")[1] + "...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println(returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("BuscarDadosEventoUsuario")) {
returnMessage = g.BuscarDadosEventoUsuario(dados.split(">")[1]);
System.out.println("Buscando dados para inscrição no evento " + dados.split(">")[1] + "...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("ReturnMessage:: " + returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("BuscarMinicursoDeEvento")) {
returnMessage = g.BuscarMinicursoDeEvento(dados.split(">")[1]);
System.out.println("Buscando minicursos do evento " + dados.split(">")[1] + "...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("ReturnMessage:: " + returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("AdicionarMinicurso")) {
returnMessage = g.adicionarMinicurso(dados.split(">")[1]);
System.out.println("Adicionando minicurso... " + dados.split(">")[1]);
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("ReturnMessage:: " + returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("AdicionarInscricao")) {
System.out.println(dados.split(">")[1]);
g.AdicionarInscricao(dados.split(">")[1]);
System.out.println("Cadastrando uma inscricao...");
} else if(dados.split(">")[0].equals("BuscarMinhasInscricoes")) {
returnMessage = g.BuscarMinhasInscricoes(dados.split(">")[1]);
System.out.println("Buscando minhas inscrições...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("ReturnMessage:: " + returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("BuscarDadosMinhaInscricao")) {
returnMessage = g.BuscarDadosMinhaInscricao(dados.split(">")[1]);
System.out.println("Buscando minhas inscrições...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("ReturnMessage:: " + returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("BuscarDescMinicursos")) {
returnMessage = g.BuscarDescMinicursos(dados.split(">")[1]);
System.out.println("Buscando minicursos...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("ReturnMessage:: " + returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("BuscarMeuPerfil")) {
returnMessage = g.BuscarMeuPerfil(dados.split(">")[1]);
System.out.println("Buscando meu perfil...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("ReturnMessage:: " + returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("ExcluirUsuario")) {
returnMessage = g.ExcluirUsuario(dados.split(">")[1]);
System.out.println("Excluindo conta do cpf " + dados.split(">")[1] + "...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println(returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("EditarPerfil")) {
returnMessage = g.EditarPerfil(dados.split(">")[1]);
//dados[1]: cpf,nome,email,dataNasc,endereco
System.out.println("Editando perfil...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
bw.flush();
} else if(dados.split(">")[0].equals("VerificarSeJaSeInscreveu")) {
returnMessage = g.VerificarSeJaSeInscreveu(dados.split(">")[1]);
//dados[1]: codEvento,email
System.out.println("Verificando se já se inscreveu no evento...");
OutputStream os = cliente.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
System.out.println("ReturnMessage:: " + returnMessage);
bw.write(returnMessage);
bw.flush();
}
cliente.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 49.554167 | 109 | 0.544858 |
4adc5ccbe627df85489941592872a662d7610c6d | 1,603 | package com.test;
public class TestString {
final static double PI=3.1415;
public static void main(String[] args) {
String a="['I6','I7','I8']";
String bStrings=a.substring(2,a.length()-2);
String[] cStrings=bStrings.split("\',\'");
System.out.println(bStrings);
for (String string : cStrings) {
System.out.println(string);
}
/*StaticTest st1=new StaticTest();
StaticTest st2=new StaticTest();
st1.method2("HAN");
*//*****����Ҫ����ת�õĶ�ά����*******//*
int arr2D[][]={{1,2,3},{4,5,6},{7,8,9}};
*//*****�������¶�ά�������ڴ��ת�ý��*******//*
���������������ע�� һ��Ҫ�ȿ���һ���ڴ棬
����ֻ�ǵ�ַ���ݣ�Ҳ����˵����������ʵ����ָ�����ͬһ���ڴ�
//�����ά�������Ϊά�������У���һ����һ������ÿһ�еij��Ȳ�һ����ͬ
int result_arr[][]=new int[arr2D.length][];//��ʵ�ֵ�һά
for(int i=0 ; i<arr2D.length;i++){ //��ʵ�ֵڶ�ά
result_arr[i]=new int[arr2D[i].length];
}
// int result_arr[][]=Arrays.copyOf(arr2D, arr2D.length);
//��������������в�ͨ��
*//*****�������ת�õĶ�ά����*******//*
for (int x[]:arr2D){
for(int e:x){
System.out.print(e+" ");
}
System.out.println();
}
System.out.println();
*//*******����Ԫ�ص���******//*
for(int i=0 ; i<arr2D.length;i++){
for(int j=0; j<arr2D[i].length;j++){
result_arr[j][i]=arr2D[i][j]; //ת�ú���
}
}
*//*****show the result in the result matrix*******//*
for (int x[]:result_arr){
for(int e:x){
System.out.print(e+" ");
}
System.out.println();
}
*/
}
}
| 25.444444 | 62 | 0.435434 |
6bae66bc5f0cb205f8edf28ccd60b2aa0e0b6283 | 14,332 | /*
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.devtools.tunnel.server;
import java.io.IOException;
import java.net.ConnectException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload;
import org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayloadForwarder;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpAsyncRequestControl;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.Assert;
/**
* A server that can be used to tunnel TCP traffic over HTTP. Similar in design to the <a
* href="http://xmpp.org/extensions/xep-0124.html">Bidirectional-streams Over Synchronous
* HTTP (BOSH)</a> XMPP extension protocol, the server uses long polling with HTTP
* requests held open until a response is available. A typical traffic pattern would be as
* follows:
*
* <pre>
* [ CLIENT ] [ SERVER ]
* | (a) Initial empty request |
* |------------------------------>|
* | (b) Data I |
* -->|------------------------------>|--->
* | Response I (a) |
* <--|<------------------------------|<---
* | |
* | (c) Data II |
* -->|------------------------------>|--->
* | Response II (b) |
* <--|<------------------------------|<---
* . .
* . .
* </pre>
*
* Each incoming request is held open to be used to carry the next available response. The
* server will hold at most two connections open at any given time.
* <p>
* Requests should be made using HTTP GET or POST (depending if there is a payload), with
* any payload contained in the body. The following response codes can be returned from
* the server:
* <table summary="Response Codes">
* <tr>
* <th>Status</th>
* <th>Meaning</th>
* </tr>
* <tr>
* <td>200 (OK)</td>
* <td>Data payload response.</td>
* </tr>
* <tr>
* <td>204 (No Content)</td>
* <td>The long poll has timed out and the client should start a new request.</td>
* </tr>
* <tr>
* <td>429 (Too many requests)</td>
* <td>There are already enough connections open, this one can be dropped.</td>
* </tr>
* <tr>
* <td>410 (Gone)</td>
* <td>The target server has disconnected.</td>
* </tr>
* </table>
* <p>
* Requests and responses that contain payloads include a {@code x-seq} header that
* contains a running sequence number (used to ensure data is applied in the correct
* order). The first request containing a payload should have a {@code x-seq} value of
* {@code 1}.
*
* @author Phillip Webb
* @since 1.3.0
* @see org.springframework.boot.devtools.tunnel.client.HttpTunnelConnection
*/
public class HttpTunnelServer {
private static final int SECONDS = 1000;
private static final int DEFAULT_LONG_POLL_TIMEOUT = 10 * SECONDS;
private static final long DEFAULT_DISCONNECT_TIMEOUT = 30 * SECONDS;
private static final MediaType DISCONNECT_MEDIA_TYPE = new MediaType("application",
"x-disconnect");
private static final Log logger = LogFactory.getLog(HttpTunnelServer.class);
private final TargetServerConnection serverConnection;
private int longPollTimeout = DEFAULT_LONG_POLL_TIMEOUT;
private long disconnectTimeout = DEFAULT_DISCONNECT_TIMEOUT;
private volatile ServerThread serverThread;
/**
* Creates a new {@link HttpTunnelServer} instance.
* @param serverConnection the connection to the target server
*/
public HttpTunnelServer(TargetServerConnection serverConnection) {
Assert.notNull(serverConnection, "ServerConnection must not be null");
this.serverConnection = serverConnection;
}
/**
* Handle an incoming HTTP connection.
* @param request the HTTP request
* @param response the HTTP response
* @throws IOException in case of I/O errors
*/
public void handle(ServerHttpRequest request, ServerHttpResponse response)
throws IOException {
handle(new HttpConnection(request, response));
}
/**
* Handle an incoming HTTP connection.
* @param httpConnection the HTTP connection
* @throws IOException in case of I/O errors
*/
protected void handle(HttpConnection httpConnection) throws IOException {
try {
getServerThread().handleIncomingHttp(httpConnection);
httpConnection.waitForResponse();
}
catch (ConnectException ex) {
httpConnection.respond(HttpStatus.GONE);
}
}
/**
* Returns the active server thread, creating and starting it if necessary.
* @return the {@code ServerThread} (never {@code null})
* @throws IOException in case of I/O errors
*/
protected ServerThread getServerThread() throws IOException {
synchronized (this) {
if (this.serverThread == null) {
ByteChannel channel = this.serverConnection.open(this.longPollTimeout);
this.serverThread = new ServerThread(channel);
this.serverThread.start();
}
return this.serverThread;
}
}
/**
* Called when the server thread exits.
*/
void clearServerThread() {
synchronized (this) {
this.serverThread = null;
}
}
/**
* Set the long poll timeout for the server.
* @param longPollTimeout the long poll timeout in milliseconds
*/
public void setLongPollTimeout(int longPollTimeout) {
Assert.isTrue(longPollTimeout > 0, "LongPollTimeout must be a positive value");
this.longPollTimeout = longPollTimeout;
}
/**
* Set the maximum amount of time to wait for a client before closing the connection.
* @param disconnectTimeout the disconnect timeout in milliseconds
*/
public void setDisconnectTimeout(long disconnectTimeout) {
Assert.isTrue(disconnectTimeout > 0, "DisconnectTimeout must be a positive value");
this.disconnectTimeout = disconnectTimeout;
}
/**
* The main server thread used to transfer tunnel traffic.
*/
protected class ServerThread extends Thread {
private final ByteChannel targetServer;
private final Deque<HttpConnection> httpConnections;
private final HttpTunnelPayloadForwarder payloadForwarder;
private boolean closed;
private AtomicLong responseSeq = new AtomicLong();
private long lastHttpRequestTime;
public ServerThread(ByteChannel targetServer) {
Assert.notNull(targetServer, "TargetServer must not be null");
this.targetServer = targetServer;
this.httpConnections = new ArrayDeque<HttpConnection>(2);
this.payloadForwarder = new HttpTunnelPayloadForwarder(targetServer);
}
@Override
public void run() {
try {
try {
readAndForwardTargetServerData();
}
catch (Exception ex) {
logger.trace("Unexpected exception from tunnel server", ex);
}
}
finally {
this.closed = true;
closeHttpConnections();
closeTargetServer();
HttpTunnelServer.this.clearServerThread();
}
}
private void readAndForwardTargetServerData() throws IOException {
while (this.targetServer.isOpen()) {
closeStaleHttpConnections();
ByteBuffer data = HttpTunnelPayload.getPayloadData(this.targetServer);
synchronized (this.httpConnections) {
if (data != null) {
HttpTunnelPayload payload = new HttpTunnelPayload(
this.responseSeq.incrementAndGet(), data);
payload.logIncoming();
HttpConnection connection = getOrWaitForHttpConnection();
connection.respond(payload);
}
}
}
}
private HttpConnection getOrWaitForHttpConnection() {
synchronized (this.httpConnections) {
HttpConnection httpConnection = this.httpConnections.pollFirst();
while (httpConnection == null) {
try {
this.httpConnections.wait(HttpTunnelServer.this.longPollTimeout);
}
catch (InterruptedException ex) {
closeHttpConnections();
}
httpConnection = this.httpConnections.pollFirst();
}
return httpConnection;
}
}
private void closeStaleHttpConnections() throws IOException {
checkNotDisconnected();
synchronized (this.httpConnections) {
Iterator<HttpConnection> iterator = this.httpConnections.iterator();
while (iterator.hasNext()) {
HttpConnection httpConnection = iterator.next();
if (httpConnection.isOlderThan(HttpTunnelServer.this.longPollTimeout)) {
httpConnection.respond(HttpStatus.NO_CONTENT);
iterator.remove();
}
}
}
}
private void checkNotDisconnected() {
long timeout = HttpTunnelServer.this.disconnectTimeout;
long duration = System.currentTimeMillis() - this.lastHttpRequestTime;
Assert.state(duration < timeout, "Disconnect timeout");
}
private void closeHttpConnections() {
synchronized (this.httpConnections) {
while (!this.httpConnections.isEmpty()) {
try {
this.httpConnections.removeFirst().respond(HttpStatus.GONE);
}
catch (Exception ex) {
logger.trace("Unable to close remote HTTP connection");
}
}
}
}
private void closeTargetServer() {
try {
this.targetServer.close();
}
catch (IOException ex) {
logger.trace("Unable to target server connection");
}
}
/**
* Handle an incoming {@link HttpConnection}.
* @param httpConnection the connection to handle.
* @throws IOException in case of I/O errors
*/
public void handleIncomingHttp(HttpConnection httpConnection) throws IOException {
if (this.closed) {
httpConnection.respond(HttpStatus.GONE);
}
synchronized (this.httpConnections) {
while (this.httpConnections.size() > 1) {
this.httpConnections.removeFirst().respond(
HttpStatus.TOO_MANY_REQUESTS);
}
this.lastHttpRequestTime = System.currentTimeMillis();
this.httpConnections.addLast(httpConnection);
this.httpConnections.notify();
}
forwardToTargetServer(httpConnection);
}
private void forwardToTargetServer(HttpConnection httpConnection)
throws IOException {
if (httpConnection.isDisconnectRequest()) {
this.targetServer.close();
interrupt();
}
ServerHttpRequest request = httpConnection.getRequest();
HttpTunnelPayload payload = HttpTunnelPayload.get(request);
if (payload != null) {
this.payloadForwarder.forward(payload);
}
}
}
/**
* Encapsulates a HTTP request/response pair.
*/
protected static class HttpConnection {
private final long createTime;
private final ServerHttpRequest request;
private final ServerHttpResponse response;
private ServerHttpAsyncRequestControl async;
private volatile boolean complete = false;
public HttpConnection(ServerHttpRequest request, ServerHttpResponse response) {
this.createTime = System.currentTimeMillis();
this.request = request;
this.response = response;
this.async = startAsync();
}
/**
* Start asynchronous support or if unavailble return {@code null} to cause
* {@link #waitForResponse()} to block.
* @return the async request control
*/
protected ServerHttpAsyncRequestControl startAsync() {
try {
// Try to use async to save blocking
ServerHttpAsyncRequestControl async = this.request
.getAsyncRequestControl(this.response);
async.start();
return async;
}
catch (Exception ex) {
return null;
}
}
/**
* Return the underlying request.
* @return the request
*/
public final ServerHttpRequest getRequest() {
return this.request;
}
/**
* Return the underlying response.
* @return the response
*/
protected final ServerHttpResponse getResponse() {
return this.response;
}
/**
* Determine if a connection is older than the specified time.
* @param time the time to check
* @return {@code true} if the request is older than the time
*/
public boolean isOlderThan(int time) {
long runningTime = System.currentTimeMillis() - this.createTime;
return (runningTime > time);
}
/**
* Cause the request to block or use asynchronous methods to wait until a response
* is available.
*/
public void waitForResponse() {
if (this.async == null) {
while (!this.complete) {
try {
synchronized (this) {
wait(1000);
}
}
catch (InterruptedException ex) {
// Ignore
}
}
}
}
/**
* Detect if the request is actually a signal to disconnect.
* @return if the request is a signal to disconnect
*/
public boolean isDisconnectRequest() {
return DISCONNECT_MEDIA_TYPE.equals(this.request.getHeaders()
.getContentType());
}
/**
* Send a HTTP status response.
* @param status the status to send
* @throws IOException in case of I/O errors
*/
public void respond(HttpStatus status) throws IOException {
Assert.notNull(status, "Status must not be null");
this.response.setStatusCode(status);
complete();
}
/**
* Send a payload response.
* @param payload the payload to send
* @throws IOException in case of I/O errors
*/
public void respond(HttpTunnelPayload payload) throws IOException {
Assert.notNull(payload, "Payload must not be null");
this.response.setStatusCode(HttpStatus.OK);
payload.assignTo(this.response);
complete();
}
/**
* Called when a request is complete.
*/
protected void complete() {
if (this.async != null) {
this.async.complete();
}
else {
synchronized (this) {
this.complete = true;
notifyAll();
}
}
}
}
}
| 29.429158 | 90 | 0.690832 |
2be276b431cb87e2c34fea55633094cddca5ca38 | 6,372 | package com.unideb.qsa.calculator.implementation.calculator;
import static com.unideb.qsa.calculator.implementation.calculator.helper.CalculatorHelper.copyOf;
import static com.unideb.qsa.calculator.implementation.calculator.helper.CalculatorHelper.factorial;
import static java.lang.Math.exp;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;
import static org.apache.commons.math3.special.Erf.erf;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.unideb.qsa.calculator.domain.SystemFeature;
/**
* System M | M | n | n Service.
*/
@Component
public class SystemMMnnCalculator {
public double BcRo(Map<SystemFeature, Double> features) {
final double c = features.get(SystemFeature.c);
final double Ro = Ro(features);
return ErlangBRecursive(c, Ro);
}
public double BcRoAppr1(Map<SystemFeature, Double> features) {
final double c = features.get(SystemFeature.c);
final double Ro = Ro(features);
final double part1 = Fix((c - Ro) / sqrt(Ro));
final double part2 = Fix((c - 1 - Ro) / sqrt(Ro));
return (part1 - part2) / part1;
}
public double BcRoAppr2(Map<SystemFeature, Double> features) {
final double c = features.get(SystemFeature.c);
final double Ro = Ro(features);
final double part1 = Fix((c - 0.5 - Ro) / sqrt(Ro));
final double part2 = Fix((c + 0.5 - Ro) / sqrt(Ro));
return 1 - part1 / part2;
}
public double BcRoAppr3(Map<SystemFeature, Double> features) {
final double c = features.get(SystemFeature.c);
final double Ro = Ro(features);
final double part1 = Fix((c + 0.5 - Ro) / sqrt(Ro));
final double part2 = Fix((c - 0.5 - Ro) / sqrt(Ro));
final double part3 = Fix((-0.5 - Ro) / sqrt(Ro));
return (part1 - part2) / (part1 - part3);
}
public double FTt(Map<SystemFeature, Double> features) {
final double t = features.get(SystemFeature.t);
final double SAvg = SAvg(features);
return 1 - exp(-1 * t / SAvg);
}
public double LambdaAvg(Map<SystemFeature, Double> features) {
final double Lambda = features.get(SystemFeature.Lambda);
final double BcRo = BcRo(features);
return Lambda * (1 - BcRo);
}
public double NAvg(Map<SystemFeature, Double> features) {
final double LambdaAvg = LambdaAvg(features);
final double SAvg = SAvg(features);
return LambdaAvg * SAvg;
}
public double D2N(Map<SystemFeature, Double> features) {
final double c = features.get(SystemFeature.c);
final double Ro = Ro(features);
final double NAvg = NAvg(features);
final double multiplication = Ro * ErlangBRecursive(c, Ro) * (c - NAvg);
return NAvg - multiplication;
}
public double P0(Map<SystemFeature, Double> features) {
final double c = features.get(SystemFeature.c);
final double Lambda = features.get(SystemFeature.Lambda);
final double Mu = features.get(SystemFeature.Mu);
double sum = 0;
for (double k = 0; k <= c; k++) {
sum += pow(Lambda / Mu, k) * (1 / factorial(k));
}
return pow(sum, -1);
}
public double Pn(Map<SystemFeature, Double> features) {
final double n = features.get(SystemFeature.n);
double result;
if (n == 0) {
result = P0(features);
} else {
final double Ro = Ro(features);
result = ErlangBRecursive(n, Ro);
}
return result;
}
public double Ro(Map<SystemFeature, Double> features) {
final double Lambda = features.get(SystemFeature.Lambda);
final double SAvg = SAvg(features);
return Lambda * SAvg;
}
public double SAvg(Map<SystemFeature, Double> features) {
final double Mu = features.get(SystemFeature.Mu);
return 1 / Mu;
}
public double TAvg(Map<SystemFeature, Double> features) {
return SAvg(features);
}
public double a(Map<SystemFeature, Double> features) {
final double c = features.get(SystemFeature.c);
final double LambdaAvg = LambdaAvg(features);
final double SAvg = SAvg(features);
return LambdaAvg * SAvg / c;
}
public double US(Map<SystemFeature, Double> features) {
final double P0 = P0(features);
return 1 - P0;
}
public double eAvg(Map<SystemFeature, Double> features) {
final double c = features.get(SystemFeature.c);
final double Mu = features.get(SystemFeature.Mu);
final double Lambda = features.get(SystemFeature.Lambda);
Map<SystemFeature, Double> PcFeatures = copyOf(features);
PcFeatures.put(SystemFeature.n, c);
final double Pc = Pn(PcFeatures);
final double divisor = Lambda * (1 - Pc);
return c / divisor - 1 / Mu;
}
public double EDeltar(Map<SystemFeature, Double> features) {
final double Lambda = features.get(SystemFeature.Lambda);
final double P0 = P0(features);
final double dividend = 1 - P0;
final double divisor = Lambda * P0;
return dividend / divisor;
}
public double ECost(Map<SystemFeature, Double> features) {
final double c = features.get(SystemFeature.c);
final double CS = features.get(SystemFeature.CS);
final double CWS = features.get(SystemFeature.CWS);
final double CI = features.get(SystemFeature.CI);
final double CSR = features.get(SystemFeature.CSR);
final double CLC = features.get(SystemFeature.CLC);
final double R = features.get(SystemFeature.R);
final double LambdaAvg = LambdaAvg(features);
final double NAvg = NAvg(features);
final double BcRo = BcRo(features);
return c * CS + NAvg * CWS + (c - NAvg) * CI + c * CSR + LambdaAvg * BcRo * CLC - LambdaAvg * R;
}
private double ErlangBRecursive(double c, double Ro) {
final double result;
if (c == 1.0) {
result = Ro / (1 + Ro);
} else {
final double recursive = Ro * ErlangBRecursive(c - 1, Ro);
result = recursive / (c + recursive);
}
return result;
}
private double Fix(double x) {
return 0.5 * (erf(x / sqrt(2)) + 1);
}
}
| 36 | 104 | 0.62194 |
1fe21ec13a66cf6d992ffb67133b87b839954ba8 | 1,152 | package com.github.akraskovski.axon.playground.queries;
import com.github.akraskovski.axon.playground.api.core.AdApprovedEvent;
import com.github.akraskovski.axon.playground.api.core.AdFinishedEvent;
import com.github.akraskovski.axon.playground.queries.domain.model.AdSummary;
import com.github.akraskovski.axon.playground.queries.domain.model.AdSummaryRepository;
import org.axonframework.modelling.saga.SagaEventHandler;
import org.axonframework.modelling.saga.SagaLifecycle;
import org.axonframework.modelling.saga.StartSaga;
import org.axonframework.spring.stereotype.Saga;
import javax.inject.Inject;
@Saga
public class AdServingSaga {
@Inject
private transient AdSummaryRepository adSummaryRepository;
@StartSaga
@SagaEventHandler(associationProperty = "adId")
public void on(AdApprovedEvent event) {
adSummaryRepository.findById(event.getAdId()).ifPresent(AdSummary::startServing);
}
@SagaEventHandler(associationProperty = "adId")
public void on(AdFinishedEvent event) {
adSummaryRepository.findById(event.getAdId()).ifPresent(AdSummary::stopServing);
SagaLifecycle.end();
}
}
| 36 | 89 | 0.795139 |
f57be41c0cc91bbda2e0b5b6336e49bf587f6b40 | 982 | package ru.yandex.qatools.allure.jenkins.utils;
import hudson.model.Result;
import java.util.Map;
/**
* @author Egor Borisov [email protected]
*/
public class BuildSummary {
private Map<String, Integer> statistics;
public BuildSummary withStatistics(final Map<String, Integer> statistics) {
this.statistics = statistics;
return this;
}
private Integer getStatistic(final String key) {
return this.statistics != null ? statistics.get(key) : 0;
}
public long getFailedCount() {
return getStatistic("failed");
}
public long getPassedCount() {
return getStatistic("passed");
}
public long getSkipCount() {
return getStatistic("skipped");
}
public long getBrokenCount() {
return getStatistic("broken");
}
public long getUnknownCount() {
return getStatistic("unknown");
}
public Result getResult() {
return Result.SUCCESS;
}
}
| 20.893617 | 79 | 0.64053 |
1f4fc43fca1fbac37b8de94d9de3392574c0c80b | 17,305 | package com.celeste.library.core.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.Arrays;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Reflection {
public static <T> Class<T> getClazz(final Object object) {
final Class<?> clazz = object.getClass();
return getClazz(clazz);
}
public static <T> Class<T> getClazz(final String path) throws ClassNotFoundException {
final Class<?> clazz = Class.forName(path);
return getClazz(clazz);
}
public static <T> Class<T> getClazz(final Field field) {
final Class<?> clazz = field.getType();
return getClazz(clazz);
}
@SuppressWarnings("unchecked")
public static <T> Class<T> getClazz(final Class<?> clazz) {
return (Class<T>) clazz;
}
public static Class<?>[] getClasses(final Object object) {
final Class<?> clazz = getClazz(object);
return getClasses(clazz);
}
public static Class<?> getClasses(final Object object, final int size) {
final Class<?> clazz = getClazz(object);
return getClasses(clazz, size);
}
public static Class<?>[] getClasses(final String path) throws ClassNotFoundException {
final Class<?> clazz = getClazz(path);
return getClasses(clazz);
}
public static Class<?> getClasses(final String path, final int size)
throws ClassNotFoundException {
final Class<?> clazz = getClazz(path);
return getClasses(clazz, size);
}
public static Class<?>[] getClasses(final Class<?> clazz) {
return clazz.getClasses();
}
public static Class<?> getClasses(final Class<?> clazz, final int size) {
return getClasses(clazz)[size];
}
public static Class<?>[] getDcClasses(final Object object) {
final Class<?> clazz = getClazz(object);
return getDcClasses(clazz);
}
public static Class<?> getDcClasses(final Object object, final int size) {
final Class<?> clazz = getClazz(object);
return getDcClasses(clazz, size);
}
public static Class<?>[] getDcClasses(final String path) throws ClassNotFoundException {
final Class<?> clazz = getClazz(path);
return getDcClasses(clazz);
}
public static Class<?> getDcClasses(final String path, final int size)
throws ClassNotFoundException {
final Class<?> clazz = getClazz(path);
return getDcClasses(clazz, size);
}
public static Class<?>[] getDcClasses(final Class<?> clazz) {
return clazz.getDeclaredClasses();
}
public static Class<?> getDcClasses(final Class<?> clazz, final int size) {
return getDcClasses(clazz)[size];
}
public static <T> Constructor<T> getConstructor(final Object object, final Class<?>... parameters)
throws NoSuchMethodException {
final Class<T> clazz = getClazz(object);
return getConstructor(clazz, parameters);
}
public static <T> Constructor<T> getConstructor(final String path, final Class<?>... parameters)
throws ClassNotFoundException, NoSuchMethodException {
final Class<T> clazz = getClazz(path);
return getConstructor(clazz, parameters);
}
public static <T> Constructor<T> getConstructor(final Class<T> clazz,
final Class<?>... parameters) throws NoSuchMethodException {
return clazz.getConstructor(parameters);
}
public static <T> Constructor<T> getDcConstructor(final Object object,
final Class<?>... parameters) throws NoSuchMethodException {
final Class<T> clazz = getClazz(object);
return getDcConstructor(clazz, parameters);
}
public static <T> Constructor<T> getDcConstructor(final String path, final Class<?>... parameters)
throws ClassNotFoundException, NoSuchMethodException {
final Class<T> clazz = getClazz(path);
return getDcConstructor(clazz, parameters);
}
public static <T> Constructor<T> getDcConstructor(final Class<T> clazz,
final Class<?>... parameters) throws NoSuchMethodException {
final Constructor<T> constructor = clazz.getDeclaredConstructor(parameters);
constructor.setAccessible(true);
return constructor;
}
public static <T> Constructor<T>[] getConstructors(final Object object) {
final Class<T> clazz = getClazz(object);
return getConstructors(clazz);
}
public static <T> Constructor<T> getConstructors(final Object object, final int size) {
final Class<T> clazz = getClazz(object);
return getConstructors(clazz, size);
}
public static <T> Constructor<T>[] getConstructors(final String path)
throws ClassNotFoundException {
final Class<T> clazz = getClazz(path);
return getConstructors(clazz);
}
public static <T> Constructor<T> getConstructors(final String path, final int size)
throws ClassNotFoundException {
final Class<T> clazz = getClazz(path);
return getConstructors(clazz, size);
}
@SuppressWarnings("unchecked")
public static <T> Constructor<T>[] getConstructors(final Class<T> clazz) {
return (Constructor<T>[]) clazz.getConstructors();
}
public static <T> Constructor<T> getConstructors(final Class<T> clazz, final int size) {
return getConstructors(clazz)[size];
}
public static <T> Constructor<T>[] getDcConstructors(final Object object) {
final Class<T> clazz = getClazz(object);
return getConstructors(clazz);
}
public static <T> Constructor<T> getDcConstructors(final Object object, final int size) {
final Class<T> clazz = getClazz(object);
return getConstructors(clazz, size);
}
public static <T> Constructor<T>[] getDcConstructors(final String path)
throws ClassNotFoundException {
final Class<T> clazz = getClazz(path);
return getConstructors(clazz);
}
public static <T> Constructor<T> getDcConstructors(final String path, final int size)
throws ClassNotFoundException {
final Class<T> clazz = getClazz(path);
return getConstructors(clazz, size);
}
@SuppressWarnings("unchecked")
public static <T> Constructor<T>[] getDcConstructors(final Class<T> clazz) {
return Arrays.stream(clazz.getDeclaredConstructors())
.peek(constructor -> constructor.setAccessible(true))
.toArray(Constructor[]::new);
}
@SuppressWarnings("unchecked")
public static <T> Constructor<T> getDcConstructors(final Class<T> clazz, final int size) {
final Constructor<T> constructor = (Constructor<T>) clazz.getDeclaredConstructors()[size];
constructor.setAccessible(true);
return constructor;
}
public static Method getMethod(final Object object, final String name,
final Class<?>... parameters) throws NoSuchMethodException {
final Class<?> clazz = getClazz(object);
return getMethod(clazz, name, parameters);
}
public static Method getMethod(final String path, final String name, final Class<?>... parameters)
throws ClassNotFoundException, NoSuchMethodException {
final Class<?> clazz = getClazz(path);
return getMethod(clazz, name, parameters);
}
public static Method getMethod(final Class<?> clazz, final String name,
final Class<?>... parameters) throws NoSuchMethodException {
return clazz.getMethod(name, parameters);
}
public static Method getDcMethod(final Object object, final String name,
final Class<?>... parameters) throws NoSuchMethodException {
final Class<?> clazz = getClazz(object);
return getDcMethod(clazz, name, parameters);
}
public static Method getDcMethod(final String path, final String name,
final Class<?>... parameters) throws ClassNotFoundException, NoSuchMethodException {
final Class<?> clazz = getClazz(path);
return getDcMethod(clazz, name, parameters);
}
public static Method getDcMethod(final Class<?> clazz, final String name,
final Class<?>... parameters) throws NoSuchMethodException {
final Method method = clazz.getDeclaredMethod(name, parameters);
method.setAccessible(true);
return method;
}
public static Method[] getMethods(final Object object) {
final Class<?> clazz = getClazz(object);
return getMethods(clazz);
}
public static Method getMethods(final Object object, final int size) {
final Class<?> clazz = getClazz(object);
return getMethods(clazz, size);
}
public static Method[] getMethods(final String path) throws ClassNotFoundException {
final Class<?> clazz = getClazz(path);
return getMethods(clazz);
}
public static Method getMethods(final String path, final int size) throws ClassNotFoundException {
final Class<?> clazz = getClazz(path);
return getMethods(clazz, size);
}
public static Method[] getMethods(final Class<?> clazz) {
return clazz.getMethods();
}
public static Method getMethods(final Class<?> clazz, final int size) {
return getMethods(clazz)[size];
}
public static Method[] getDcMethods(final Object object) {
final Class<?> clazz = getClazz(object);
return getDcMethods(clazz);
}
public static Method getDcMethods(final Object object, final int size) {
final Class<?> clazz = getClazz(object);
return getDcMethods(clazz, size);
}
public static Method[] getDcMethods(final String path) throws ClassNotFoundException {
final Class<?> clazz = getClazz(path);
return getDcMethods(clazz);
}
public static Method getDcMethods(final String path, final int size)
throws ClassNotFoundException {
final Class<?> clazz = getClazz(path);
return getDcMethods(clazz, size);
}
public static Method[] getDcMethods(final Class<?> clazz) {
return Arrays.stream(clazz.getDeclaredMethods())
.peek(method -> method.setAccessible(true))
.toArray(Method[]::new);
}
public static Method getDcMethods(final Class<?> clazz, final int size) {
final Method method = clazz.getDeclaredMethods()[size];
method.setAccessible(true);
return method;
}
public static Field getField(final Object object, final String name) throws NoSuchFieldException {
final Class<?> clazz = getClazz(object);
return getField(clazz, name);
}
public static Field getField(final String path, final String name)
throws ClassNotFoundException, NoSuchFieldException {
final Class<?> clazz = getClazz(path);
return getField(clazz, name);
}
public static Field getField(final Class<?> clazz, final String name)
throws NoSuchFieldException {
return clazz.getField(name);
}
public static Field getDcField(final Object object, final String name)
throws NoSuchFieldException {
final Class<?> clazz = getClazz(object);
return getDcField(clazz, name);
}
public static Field getDcField(final String path, final String name)
throws ClassNotFoundException, NoSuchFieldException {
final Class<?> clazz = getClazz(path);
return getDcField(clazz, name);
}
public static Field getDcField(final Class<?> clazz, final String name)
throws NoSuchFieldException {
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
}
public static Field[] getFields(final Object object) {
final Class<?> clazz = getClazz(object);
return getFields(clazz);
}
public static Field getFields(final Object object, final int size) {
final Class<?> clazz = getClazz(object);
return getFields(clazz, size);
}
public static Field[] getFields(final String path) throws ClassNotFoundException {
final Class<?> clazz = getClazz(path);
return getFields(clazz);
}
public static Field getFields(final String path, final int size) throws ClassNotFoundException {
final Class<?> clazz = getClazz(path);
return getFields(clazz, size);
}
public static Field[] getFields(final Class<?> clazz) {
return clazz.getFields();
}
public static Field getFields(final Class<?> clazz, final int size) {
return getFields(clazz)[size];
}
public static Field[] getDcFields(final Object object) {
final Class<?> clazz = getClazz(object);
return getDcFields(clazz);
}
public static Field getDcFields(final Object object, final int size) {
final Class<?> clazz = getClazz(object);
return getDcFields(clazz, size);
}
public static Field[] getDcFields(final String path) throws ClassNotFoundException {
final Class<?> clazz = getClazz(path);
return getDcFields(clazz);
}
public static Field getDcFields(final String path, final int size) throws ClassNotFoundException {
final Class<?> clazz = getClazz(path);
return getDcFields(clazz, size);
}
public static Field[] getDcFields(final Class<?> clazz) {
return Arrays.stream(clazz.getDeclaredFields())
.peek(field -> field.setAccessible(true))
.toArray(Field[]::new);
}
public static Field getDcFields(final Class<?> clazz, final int size) {
final Field field = clazz.getDeclaredFields()[size];
field.setAccessible(true);
return field;
}
public static <T extends Annotation> boolean containsAnnotation(final Class<?> clazz,
final Class<T> annotation) {
return clazz.isAnnotationPresent(annotation);
}
public static <T extends Annotation> boolean containsAnnotation(final Constructor<?> constructor,
final Class<T> annotation) {
return constructor.isAnnotationPresent(annotation);
}
public static <T extends Annotation> boolean containsAnnotation(final Field field,
final Class<T> annotation) {
return field.isAnnotationPresent(annotation);
}
public static <T extends Annotation> T getAnnotation(final Class<?> clazz,
final Class<T> annotation) {
return clazz.getAnnotation(annotation);
}
public static <T extends Annotation> T getAnnotation(final Constructor<?> constructor,
final Class<T> annotation) {
return constructor.getAnnotation(annotation);
}
public static <T extends Annotation> T getAnnotation(final Field field,
final Class<T> annotation) {
return field.getAnnotation(annotation);
}
public static <T> T instance(final Object object)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException,
InstantiationException {
final Constructor<T> constructor = getConstructor(object);
return instance(constructor);
}
public static <T> T instance(final Class<T> clazz)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException,
InstantiationException {
final Constructor<T> constructor = getConstructor(clazz);
return instance(constructor);
}
public static <T> T instance(final Constructor<T> constructor)
throws IllegalAccessException, InvocationTargetException, InstantiationException {
return constructor.newInstance();
}
public static <T> T instance(final Constructor<T> constructor, final Object... arguments)
throws IllegalAccessException, InvocationTargetException, InstantiationException {
return constructor.newInstance(arguments);
}
public static Object getValueFromEnum(final Class<?> enumClass, final String enumName) {
return Enum.valueOf(enumClass.asSubclass(Enum.class), enumName);
}
public static Object getValueFromEnum(final Class<?> enumClass, final String enumName, final int fallbackOrdinal) {
try {
return getValueFromEnum(enumClass, enumName);
} catch (IllegalArgumentException exception) {
final Object[] constants = enumClass.getEnumConstants();
if (constants.length > fallbackOrdinal) {
return constants[fallbackOrdinal];
}
throw exception;
}
}
@SuppressWarnings("unchecked")
public static <T> T invoke(final Method method, final Object instance, final Object... arguments)
throws InvocationTargetException, IllegalAccessException {
return (T) method.invoke(instance, arguments);
}
public static <T> T invokeStatic(final Method method, final Object... arguments)
throws InvocationTargetException, IllegalAccessException {
return invoke(method, null, arguments);
}
@SuppressWarnings("unchecked")
public static <T> T get(final Field field, final Object instance) throws IllegalAccessException {
return (T) field.get(instance);
}
public static <T> T getStatic(final Field field) throws IllegalAccessException {
return get(field, null);
}
public static void setField(final Object object, final Class<?> fieldType, final Object value) throws ReflectiveOperationException {
final Field[] fields = Arrays.stream(object.getClass().getDeclaredFields())
.filter((field) -> !Modifier.isStatic(field.getModifiers()))
.toArray(Field[]::new);
for (Field field : fields) {
if (field.getType() == fieldType) {
field.set(object, value);
}
}
}
}
| 35.388548 | 134 | 0.689396 |
f519d3b55f0dfb4e96458f3cecbfb4b7236c3c8f | 90,303 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/metric.proto
package com.google.monitoring.v3;
/**
* <pre>
* Represents the values of a time series associated with a
* TimeSeriesDescriptor.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.TimeSeriesData}
*/
public final class TimeSeriesData extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.monitoring.v3.TimeSeriesData)
TimeSeriesDataOrBuilder {
private static final long serialVersionUID = 0L;
// Use TimeSeriesData.newBuilder() to construct.
private TimeSeriesData(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private TimeSeriesData() {
labelValues_ = java.util.Collections.emptyList();
pointData_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new TimeSeriesData();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private TimeSeriesData(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
labelValues_ = new java.util.ArrayList<com.google.monitoring.v3.LabelValue>();
mutable_bitField0_ |= 0x00000001;
}
labelValues_.add(
input.readMessage(com.google.monitoring.v3.LabelValue.parser(), extensionRegistry));
break;
}
case 18: {
if (!((mutable_bitField0_ & 0x00000002) != 0)) {
pointData_ = new java.util.ArrayList<com.google.monitoring.v3.TimeSeriesData.PointData>();
mutable_bitField0_ |= 0x00000002;
}
pointData_.add(
input.readMessage(com.google.monitoring.v3.TimeSeriesData.PointData.parser(), extensionRegistry));
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
labelValues_ = java.util.Collections.unmodifiableList(labelValues_);
}
if (((mutable_bitField0_ & 0x00000002) != 0)) {
pointData_ = java.util.Collections.unmodifiableList(pointData_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.monitoring.v3.MetricProto.internal_static_google_monitoring_v3_TimeSeriesData_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.MetricProto.internal_static_google_monitoring_v3_TimeSeriesData_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.TimeSeriesData.class, com.google.monitoring.v3.TimeSeriesData.Builder.class);
}
public interface PointDataOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.monitoring.v3.TimeSeriesData.PointData)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
java.util.List<com.google.monitoring.v3.TypedValue>
getValuesList();
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
com.google.monitoring.v3.TypedValue getValues(int index);
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
int getValuesCount();
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
java.util.List<? extends com.google.monitoring.v3.TypedValueOrBuilder>
getValuesOrBuilderList();
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
com.google.monitoring.v3.TypedValueOrBuilder getValuesOrBuilder(
int index);
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
* @return Whether the timeInterval field is set.
*/
boolean hasTimeInterval();
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
* @return The timeInterval.
*/
com.google.monitoring.v3.TimeInterval getTimeInterval();
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
*/
com.google.monitoring.v3.TimeIntervalOrBuilder getTimeIntervalOrBuilder();
}
/**
* <pre>
* A point's value columns and time interval. Each point has one or more
* point values corresponding to the entries in `point_descriptors` field in
* the TimeSeriesDescriptor associated with this object.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.TimeSeriesData.PointData}
*/
public static final class PointData extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.monitoring.v3.TimeSeriesData.PointData)
PointDataOrBuilder {
private static final long serialVersionUID = 0L;
// Use PointData.newBuilder() to construct.
private PointData(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PointData() {
values_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new PointData();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private PointData(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
values_ = new java.util.ArrayList<com.google.monitoring.v3.TypedValue>();
mutable_bitField0_ |= 0x00000001;
}
values_.add(
input.readMessage(com.google.monitoring.v3.TypedValue.parser(), extensionRegistry));
break;
}
case 18: {
com.google.monitoring.v3.TimeInterval.Builder subBuilder = null;
if (timeInterval_ != null) {
subBuilder = timeInterval_.toBuilder();
}
timeInterval_ = input.readMessage(com.google.monitoring.v3.TimeInterval.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(timeInterval_);
timeInterval_ = subBuilder.buildPartial();
}
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
values_ = java.util.Collections.unmodifiableList(values_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.monitoring.v3.MetricProto.internal_static_google_monitoring_v3_TimeSeriesData_PointData_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.MetricProto.internal_static_google_monitoring_v3_TimeSeriesData_PointData_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.TimeSeriesData.PointData.class, com.google.monitoring.v3.TimeSeriesData.PointData.Builder.class);
}
public static final int VALUES_FIELD_NUMBER = 1;
private java.util.List<com.google.monitoring.v3.TypedValue> values_;
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.monitoring.v3.TypedValue> getValuesList() {
return values_;
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.monitoring.v3.TypedValueOrBuilder>
getValuesOrBuilderList() {
return values_;
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
@java.lang.Override
public int getValuesCount() {
return values_.size();
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.TypedValue getValues(int index) {
return values_.get(index);
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.TypedValueOrBuilder getValuesOrBuilder(
int index) {
return values_.get(index);
}
public static final int TIME_INTERVAL_FIELD_NUMBER = 2;
private com.google.monitoring.v3.TimeInterval timeInterval_;
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
* @return Whether the timeInterval field is set.
*/
@java.lang.Override
public boolean hasTimeInterval() {
return timeInterval_ != null;
}
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
* @return The timeInterval.
*/
@java.lang.Override
public com.google.monitoring.v3.TimeInterval getTimeInterval() {
return timeInterval_ == null ? com.google.monitoring.v3.TimeInterval.getDefaultInstance() : timeInterval_;
}
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.TimeIntervalOrBuilder getTimeIntervalOrBuilder() {
return getTimeInterval();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
for (int i = 0; i < values_.size(); i++) {
output.writeMessage(1, values_.get(i));
}
if (timeInterval_ != null) {
output.writeMessage(2, getTimeInterval());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < values_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, values_.get(i));
}
if (timeInterval_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getTimeInterval());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.monitoring.v3.TimeSeriesData.PointData)) {
return super.equals(obj);
}
com.google.monitoring.v3.TimeSeriesData.PointData other = (com.google.monitoring.v3.TimeSeriesData.PointData) obj;
if (!getValuesList()
.equals(other.getValuesList())) return false;
if (hasTimeInterval() != other.hasTimeInterval()) return false;
if (hasTimeInterval()) {
if (!getTimeInterval()
.equals(other.getTimeInterval())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getValuesCount() > 0) {
hash = (37 * hash) + VALUES_FIELD_NUMBER;
hash = (53 * hash) + getValuesList().hashCode();
}
if (hasTimeInterval()) {
hash = (37 * hash) + TIME_INTERVAL_FIELD_NUMBER;
hash = (53 * hash) + getTimeInterval().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.monitoring.v3.TimeSeriesData.PointData parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.TimeSeriesData.PointData parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.TimeSeriesData.PointData parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.TimeSeriesData.PointData parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.TimeSeriesData.PointData parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.TimeSeriesData.PointData parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.TimeSeriesData.PointData parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.TimeSeriesData.PointData parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.TimeSeriesData.PointData parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.TimeSeriesData.PointData parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.TimeSeriesData.PointData parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.TimeSeriesData.PointData parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.monitoring.v3.TimeSeriesData.PointData prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* A point's value columns and time interval. Each point has one or more
* point values corresponding to the entries in `point_descriptors` field in
* the TimeSeriesDescriptor associated with this object.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.TimeSeriesData.PointData}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.monitoring.v3.TimeSeriesData.PointData)
com.google.monitoring.v3.TimeSeriesData.PointDataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.monitoring.v3.MetricProto.internal_static_google_monitoring_v3_TimeSeriesData_PointData_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.MetricProto.internal_static_google_monitoring_v3_TimeSeriesData_PointData_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.TimeSeriesData.PointData.class, com.google.monitoring.v3.TimeSeriesData.PointData.Builder.class);
}
// Construct using com.google.monitoring.v3.TimeSeriesData.PointData.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getValuesFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (valuesBuilder_ == null) {
values_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
valuesBuilder_.clear();
}
if (timeIntervalBuilder_ == null) {
timeInterval_ = null;
} else {
timeInterval_ = null;
timeIntervalBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.monitoring.v3.MetricProto.internal_static_google_monitoring_v3_TimeSeriesData_PointData_descriptor;
}
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesData.PointData getDefaultInstanceForType() {
return com.google.monitoring.v3.TimeSeriesData.PointData.getDefaultInstance();
}
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesData.PointData build() {
com.google.monitoring.v3.TimeSeriesData.PointData result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesData.PointData buildPartial() {
com.google.monitoring.v3.TimeSeriesData.PointData result = new com.google.monitoring.v3.TimeSeriesData.PointData(this);
int from_bitField0_ = bitField0_;
if (valuesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
values_ = java.util.Collections.unmodifiableList(values_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.values_ = values_;
} else {
result.values_ = valuesBuilder_.build();
}
if (timeIntervalBuilder_ == null) {
result.timeInterval_ = timeInterval_;
} else {
result.timeInterval_ = timeIntervalBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.monitoring.v3.TimeSeriesData.PointData) {
return mergeFrom((com.google.monitoring.v3.TimeSeriesData.PointData)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.monitoring.v3.TimeSeriesData.PointData other) {
if (other == com.google.monitoring.v3.TimeSeriesData.PointData.getDefaultInstance()) return this;
if (valuesBuilder_ == null) {
if (!other.values_.isEmpty()) {
if (values_.isEmpty()) {
values_ = other.values_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureValuesIsMutable();
values_.addAll(other.values_);
}
onChanged();
}
} else {
if (!other.values_.isEmpty()) {
if (valuesBuilder_.isEmpty()) {
valuesBuilder_.dispose();
valuesBuilder_ = null;
values_ = other.values_;
bitField0_ = (bitField0_ & ~0x00000001);
valuesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getValuesFieldBuilder() : null;
} else {
valuesBuilder_.addAllMessages(other.values_);
}
}
}
if (other.hasTimeInterval()) {
mergeTimeInterval(other.getTimeInterval());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.monitoring.v3.TimeSeriesData.PointData parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.monitoring.v3.TimeSeriesData.PointData) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<com.google.monitoring.v3.TypedValue> values_ =
java.util.Collections.emptyList();
private void ensureValuesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
values_ = new java.util.ArrayList<com.google.monitoring.v3.TypedValue>(values_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.monitoring.v3.TypedValue, com.google.monitoring.v3.TypedValue.Builder, com.google.monitoring.v3.TypedValueOrBuilder> valuesBuilder_;
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public java.util.List<com.google.monitoring.v3.TypedValue> getValuesList() {
if (valuesBuilder_ == null) {
return java.util.Collections.unmodifiableList(values_);
} else {
return valuesBuilder_.getMessageList();
}
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public int getValuesCount() {
if (valuesBuilder_ == null) {
return values_.size();
} else {
return valuesBuilder_.getCount();
}
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public com.google.monitoring.v3.TypedValue getValues(int index) {
if (valuesBuilder_ == null) {
return values_.get(index);
} else {
return valuesBuilder_.getMessage(index);
}
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public Builder setValues(
int index, com.google.monitoring.v3.TypedValue value) {
if (valuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureValuesIsMutable();
values_.set(index, value);
onChanged();
} else {
valuesBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public Builder setValues(
int index, com.google.monitoring.v3.TypedValue.Builder builderForValue) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
values_.set(index, builderForValue.build());
onChanged();
} else {
valuesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public Builder addValues(com.google.monitoring.v3.TypedValue value) {
if (valuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureValuesIsMutable();
values_.add(value);
onChanged();
} else {
valuesBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public Builder addValues(
int index, com.google.monitoring.v3.TypedValue value) {
if (valuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureValuesIsMutable();
values_.add(index, value);
onChanged();
} else {
valuesBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public Builder addValues(
com.google.monitoring.v3.TypedValue.Builder builderForValue) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
values_.add(builderForValue.build());
onChanged();
} else {
valuesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public Builder addValues(
int index, com.google.monitoring.v3.TypedValue.Builder builderForValue) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
values_.add(index, builderForValue.build());
onChanged();
} else {
valuesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public Builder addAllValues(
java.lang.Iterable<? extends com.google.monitoring.v3.TypedValue> values) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, values_);
onChanged();
} else {
valuesBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public Builder clearValues() {
if (valuesBuilder_ == null) {
values_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
valuesBuilder_.clear();
}
return this;
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public Builder removeValues(int index) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
values_.remove(index);
onChanged();
} else {
valuesBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public com.google.monitoring.v3.TypedValue.Builder getValuesBuilder(
int index) {
return getValuesFieldBuilder().getBuilder(index);
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public com.google.monitoring.v3.TypedValueOrBuilder getValuesOrBuilder(
int index) {
if (valuesBuilder_ == null) {
return values_.get(index); } else {
return valuesBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public java.util.List<? extends com.google.monitoring.v3.TypedValueOrBuilder>
getValuesOrBuilderList() {
if (valuesBuilder_ != null) {
return valuesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(values_);
}
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public com.google.monitoring.v3.TypedValue.Builder addValuesBuilder() {
return getValuesFieldBuilder().addBuilder(
com.google.monitoring.v3.TypedValue.getDefaultInstance());
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public com.google.monitoring.v3.TypedValue.Builder addValuesBuilder(
int index) {
return getValuesFieldBuilder().addBuilder(
index, com.google.monitoring.v3.TypedValue.getDefaultInstance());
}
/**
* <pre>
* The values that make up the point.
* </pre>
*
* <code>repeated .google.monitoring.v3.TypedValue values = 1;</code>
*/
public java.util.List<com.google.monitoring.v3.TypedValue.Builder>
getValuesBuilderList() {
return getValuesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.monitoring.v3.TypedValue, com.google.monitoring.v3.TypedValue.Builder, com.google.monitoring.v3.TypedValueOrBuilder>
getValuesFieldBuilder() {
if (valuesBuilder_ == null) {
valuesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.monitoring.v3.TypedValue, com.google.monitoring.v3.TypedValue.Builder, com.google.monitoring.v3.TypedValueOrBuilder>(
values_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
values_ = null;
}
return valuesBuilder_;
}
private com.google.monitoring.v3.TimeInterval timeInterval_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.TimeInterval, com.google.monitoring.v3.TimeInterval.Builder, com.google.monitoring.v3.TimeIntervalOrBuilder> timeIntervalBuilder_;
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
* @return Whether the timeInterval field is set.
*/
public boolean hasTimeInterval() {
return timeIntervalBuilder_ != null || timeInterval_ != null;
}
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
* @return The timeInterval.
*/
public com.google.monitoring.v3.TimeInterval getTimeInterval() {
if (timeIntervalBuilder_ == null) {
return timeInterval_ == null ? com.google.monitoring.v3.TimeInterval.getDefaultInstance() : timeInterval_;
} else {
return timeIntervalBuilder_.getMessage();
}
}
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
*/
public Builder setTimeInterval(com.google.monitoring.v3.TimeInterval value) {
if (timeIntervalBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
timeInterval_ = value;
onChanged();
} else {
timeIntervalBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
*/
public Builder setTimeInterval(
com.google.monitoring.v3.TimeInterval.Builder builderForValue) {
if (timeIntervalBuilder_ == null) {
timeInterval_ = builderForValue.build();
onChanged();
} else {
timeIntervalBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
*/
public Builder mergeTimeInterval(com.google.monitoring.v3.TimeInterval value) {
if (timeIntervalBuilder_ == null) {
if (timeInterval_ != null) {
timeInterval_ =
com.google.monitoring.v3.TimeInterval.newBuilder(timeInterval_).mergeFrom(value).buildPartial();
} else {
timeInterval_ = value;
}
onChanged();
} else {
timeIntervalBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
*/
public Builder clearTimeInterval() {
if (timeIntervalBuilder_ == null) {
timeInterval_ = null;
onChanged();
} else {
timeInterval_ = null;
timeIntervalBuilder_ = null;
}
return this;
}
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
*/
public com.google.monitoring.v3.TimeInterval.Builder getTimeIntervalBuilder() {
onChanged();
return getTimeIntervalFieldBuilder().getBuilder();
}
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
*/
public com.google.monitoring.v3.TimeIntervalOrBuilder getTimeIntervalOrBuilder() {
if (timeIntervalBuilder_ != null) {
return timeIntervalBuilder_.getMessageOrBuilder();
} else {
return timeInterval_ == null ?
com.google.monitoring.v3.TimeInterval.getDefaultInstance() : timeInterval_;
}
}
/**
* <pre>
* The time interval associated with the point.
* </pre>
*
* <code>.google.monitoring.v3.TimeInterval time_interval = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.TimeInterval, com.google.monitoring.v3.TimeInterval.Builder, com.google.monitoring.v3.TimeIntervalOrBuilder>
getTimeIntervalFieldBuilder() {
if (timeIntervalBuilder_ == null) {
timeIntervalBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.monitoring.v3.TimeInterval, com.google.monitoring.v3.TimeInterval.Builder, com.google.monitoring.v3.TimeIntervalOrBuilder>(
getTimeInterval(),
getParentForChildren(),
isClean());
timeInterval_ = null;
}
return timeIntervalBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.monitoring.v3.TimeSeriesData.PointData)
}
// @@protoc_insertion_point(class_scope:google.monitoring.v3.TimeSeriesData.PointData)
private static final com.google.monitoring.v3.TimeSeriesData.PointData DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.monitoring.v3.TimeSeriesData.PointData();
}
public static com.google.monitoring.v3.TimeSeriesData.PointData getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<PointData>
PARSER = new com.google.protobuf.AbstractParser<PointData>() {
@java.lang.Override
public PointData parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new PointData(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<PointData> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PointData> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesData.PointData getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public static final int LABEL_VALUES_FIELD_NUMBER = 1;
private java.util.List<com.google.monitoring.v3.LabelValue> labelValues_;
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.monitoring.v3.LabelValue> getLabelValuesList() {
return labelValues_;
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.monitoring.v3.LabelValueOrBuilder>
getLabelValuesOrBuilderList() {
return labelValues_;
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
@java.lang.Override
public int getLabelValuesCount() {
return labelValues_.size();
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.LabelValue getLabelValues(int index) {
return labelValues_.get(index);
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.LabelValueOrBuilder getLabelValuesOrBuilder(
int index) {
return labelValues_.get(index);
}
public static final int POINT_DATA_FIELD_NUMBER = 2;
private java.util.List<com.google.monitoring.v3.TimeSeriesData.PointData> pointData_;
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
@java.lang.Override
public java.util.List<com.google.monitoring.v3.TimeSeriesData.PointData> getPointDataList() {
return pointData_;
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.monitoring.v3.TimeSeriesData.PointDataOrBuilder>
getPointDataOrBuilderList() {
return pointData_;
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
@java.lang.Override
public int getPointDataCount() {
return pointData_.size();
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesData.PointData getPointData(int index) {
return pointData_.get(index);
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesData.PointDataOrBuilder getPointDataOrBuilder(
int index) {
return pointData_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
for (int i = 0; i < labelValues_.size(); i++) {
output.writeMessage(1, labelValues_.get(i));
}
for (int i = 0; i < pointData_.size(); i++) {
output.writeMessage(2, pointData_.get(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < labelValues_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, labelValues_.get(i));
}
for (int i = 0; i < pointData_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, pointData_.get(i));
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.monitoring.v3.TimeSeriesData)) {
return super.equals(obj);
}
com.google.monitoring.v3.TimeSeriesData other = (com.google.monitoring.v3.TimeSeriesData) obj;
if (!getLabelValuesList()
.equals(other.getLabelValuesList())) return false;
if (!getPointDataList()
.equals(other.getPointDataList())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getLabelValuesCount() > 0) {
hash = (37 * hash) + LABEL_VALUES_FIELD_NUMBER;
hash = (53 * hash) + getLabelValuesList().hashCode();
}
if (getPointDataCount() > 0) {
hash = (37 * hash) + POINT_DATA_FIELD_NUMBER;
hash = (53 * hash) + getPointDataList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.monitoring.v3.TimeSeriesData parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.TimeSeriesData parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.TimeSeriesData parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.TimeSeriesData parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.TimeSeriesData parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.TimeSeriesData parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.TimeSeriesData parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.TimeSeriesData parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.TimeSeriesData parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.TimeSeriesData parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.TimeSeriesData parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.TimeSeriesData parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.monitoring.v3.TimeSeriesData prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Represents the values of a time series associated with a
* TimeSeriesDescriptor.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.TimeSeriesData}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.monitoring.v3.TimeSeriesData)
com.google.monitoring.v3.TimeSeriesDataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.monitoring.v3.MetricProto.internal_static_google_monitoring_v3_TimeSeriesData_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.MetricProto.internal_static_google_monitoring_v3_TimeSeriesData_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.TimeSeriesData.class, com.google.monitoring.v3.TimeSeriesData.Builder.class);
}
// Construct using com.google.monitoring.v3.TimeSeriesData.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getLabelValuesFieldBuilder();
getPointDataFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (labelValuesBuilder_ == null) {
labelValues_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
labelValuesBuilder_.clear();
}
if (pointDataBuilder_ == null) {
pointData_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
} else {
pointDataBuilder_.clear();
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.monitoring.v3.MetricProto.internal_static_google_monitoring_v3_TimeSeriesData_descriptor;
}
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesData getDefaultInstanceForType() {
return com.google.monitoring.v3.TimeSeriesData.getDefaultInstance();
}
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesData build() {
com.google.monitoring.v3.TimeSeriesData result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesData buildPartial() {
com.google.monitoring.v3.TimeSeriesData result = new com.google.monitoring.v3.TimeSeriesData(this);
int from_bitField0_ = bitField0_;
if (labelValuesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
labelValues_ = java.util.Collections.unmodifiableList(labelValues_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.labelValues_ = labelValues_;
} else {
result.labelValues_ = labelValuesBuilder_.build();
}
if (pointDataBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)) {
pointData_ = java.util.Collections.unmodifiableList(pointData_);
bitField0_ = (bitField0_ & ~0x00000002);
}
result.pointData_ = pointData_;
} else {
result.pointData_ = pointDataBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.monitoring.v3.TimeSeriesData) {
return mergeFrom((com.google.monitoring.v3.TimeSeriesData)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.monitoring.v3.TimeSeriesData other) {
if (other == com.google.monitoring.v3.TimeSeriesData.getDefaultInstance()) return this;
if (labelValuesBuilder_ == null) {
if (!other.labelValues_.isEmpty()) {
if (labelValues_.isEmpty()) {
labelValues_ = other.labelValues_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureLabelValuesIsMutable();
labelValues_.addAll(other.labelValues_);
}
onChanged();
}
} else {
if (!other.labelValues_.isEmpty()) {
if (labelValuesBuilder_.isEmpty()) {
labelValuesBuilder_.dispose();
labelValuesBuilder_ = null;
labelValues_ = other.labelValues_;
bitField0_ = (bitField0_ & ~0x00000001);
labelValuesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getLabelValuesFieldBuilder() : null;
} else {
labelValuesBuilder_.addAllMessages(other.labelValues_);
}
}
}
if (pointDataBuilder_ == null) {
if (!other.pointData_.isEmpty()) {
if (pointData_.isEmpty()) {
pointData_ = other.pointData_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensurePointDataIsMutable();
pointData_.addAll(other.pointData_);
}
onChanged();
}
} else {
if (!other.pointData_.isEmpty()) {
if (pointDataBuilder_.isEmpty()) {
pointDataBuilder_.dispose();
pointDataBuilder_ = null;
pointData_ = other.pointData_;
bitField0_ = (bitField0_ & ~0x00000002);
pointDataBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getPointDataFieldBuilder() : null;
} else {
pointDataBuilder_.addAllMessages(other.pointData_);
}
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.monitoring.v3.TimeSeriesData parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.monitoring.v3.TimeSeriesData) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<com.google.monitoring.v3.LabelValue> labelValues_ =
java.util.Collections.emptyList();
private void ensureLabelValuesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
labelValues_ = new java.util.ArrayList<com.google.monitoring.v3.LabelValue>(labelValues_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.monitoring.v3.LabelValue, com.google.monitoring.v3.LabelValue.Builder, com.google.monitoring.v3.LabelValueOrBuilder> labelValuesBuilder_;
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public java.util.List<com.google.monitoring.v3.LabelValue> getLabelValuesList() {
if (labelValuesBuilder_ == null) {
return java.util.Collections.unmodifiableList(labelValues_);
} else {
return labelValuesBuilder_.getMessageList();
}
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public int getLabelValuesCount() {
if (labelValuesBuilder_ == null) {
return labelValues_.size();
} else {
return labelValuesBuilder_.getCount();
}
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public com.google.monitoring.v3.LabelValue getLabelValues(int index) {
if (labelValuesBuilder_ == null) {
return labelValues_.get(index);
} else {
return labelValuesBuilder_.getMessage(index);
}
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public Builder setLabelValues(
int index, com.google.monitoring.v3.LabelValue value) {
if (labelValuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureLabelValuesIsMutable();
labelValues_.set(index, value);
onChanged();
} else {
labelValuesBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public Builder setLabelValues(
int index, com.google.monitoring.v3.LabelValue.Builder builderForValue) {
if (labelValuesBuilder_ == null) {
ensureLabelValuesIsMutable();
labelValues_.set(index, builderForValue.build());
onChanged();
} else {
labelValuesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public Builder addLabelValues(com.google.monitoring.v3.LabelValue value) {
if (labelValuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureLabelValuesIsMutable();
labelValues_.add(value);
onChanged();
} else {
labelValuesBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public Builder addLabelValues(
int index, com.google.monitoring.v3.LabelValue value) {
if (labelValuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureLabelValuesIsMutable();
labelValues_.add(index, value);
onChanged();
} else {
labelValuesBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public Builder addLabelValues(
com.google.monitoring.v3.LabelValue.Builder builderForValue) {
if (labelValuesBuilder_ == null) {
ensureLabelValuesIsMutable();
labelValues_.add(builderForValue.build());
onChanged();
} else {
labelValuesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public Builder addLabelValues(
int index, com.google.monitoring.v3.LabelValue.Builder builderForValue) {
if (labelValuesBuilder_ == null) {
ensureLabelValuesIsMutable();
labelValues_.add(index, builderForValue.build());
onChanged();
} else {
labelValuesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public Builder addAllLabelValues(
java.lang.Iterable<? extends com.google.monitoring.v3.LabelValue> values) {
if (labelValuesBuilder_ == null) {
ensureLabelValuesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, labelValues_);
onChanged();
} else {
labelValuesBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public Builder clearLabelValues() {
if (labelValuesBuilder_ == null) {
labelValues_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
labelValuesBuilder_.clear();
}
return this;
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public Builder removeLabelValues(int index) {
if (labelValuesBuilder_ == null) {
ensureLabelValuesIsMutable();
labelValues_.remove(index);
onChanged();
} else {
labelValuesBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public com.google.monitoring.v3.LabelValue.Builder getLabelValuesBuilder(
int index) {
return getLabelValuesFieldBuilder().getBuilder(index);
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public com.google.monitoring.v3.LabelValueOrBuilder getLabelValuesOrBuilder(
int index) {
if (labelValuesBuilder_ == null) {
return labelValues_.get(index); } else {
return labelValuesBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public java.util.List<? extends com.google.monitoring.v3.LabelValueOrBuilder>
getLabelValuesOrBuilderList() {
if (labelValuesBuilder_ != null) {
return labelValuesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(labelValues_);
}
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public com.google.monitoring.v3.LabelValue.Builder addLabelValuesBuilder() {
return getLabelValuesFieldBuilder().addBuilder(
com.google.monitoring.v3.LabelValue.getDefaultInstance());
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public com.google.monitoring.v3.LabelValue.Builder addLabelValuesBuilder(
int index) {
return getLabelValuesFieldBuilder().addBuilder(
index, com.google.monitoring.v3.LabelValue.getDefaultInstance());
}
/**
* <pre>
* The values of the labels in the time series identifier, given in the same
* order as the `label_descriptors` field of the TimeSeriesDescriptor
* associated with this object. Each value must have a value of the type
* given in the corresponding entry of `label_descriptors`.
* </pre>
*
* <code>repeated .google.monitoring.v3.LabelValue label_values = 1;</code>
*/
public java.util.List<com.google.monitoring.v3.LabelValue.Builder>
getLabelValuesBuilderList() {
return getLabelValuesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.monitoring.v3.LabelValue, com.google.monitoring.v3.LabelValue.Builder, com.google.monitoring.v3.LabelValueOrBuilder>
getLabelValuesFieldBuilder() {
if (labelValuesBuilder_ == null) {
labelValuesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.monitoring.v3.LabelValue, com.google.monitoring.v3.LabelValue.Builder, com.google.monitoring.v3.LabelValueOrBuilder>(
labelValues_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
labelValues_ = null;
}
return labelValuesBuilder_;
}
private java.util.List<com.google.monitoring.v3.TimeSeriesData.PointData> pointData_ =
java.util.Collections.emptyList();
private void ensurePointDataIsMutable() {
if (!((bitField0_ & 0x00000002) != 0)) {
pointData_ = new java.util.ArrayList<com.google.monitoring.v3.TimeSeriesData.PointData>(pointData_);
bitField0_ |= 0x00000002;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.monitoring.v3.TimeSeriesData.PointData, com.google.monitoring.v3.TimeSeriesData.PointData.Builder, com.google.monitoring.v3.TimeSeriesData.PointDataOrBuilder> pointDataBuilder_;
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public java.util.List<com.google.monitoring.v3.TimeSeriesData.PointData> getPointDataList() {
if (pointDataBuilder_ == null) {
return java.util.Collections.unmodifiableList(pointData_);
} else {
return pointDataBuilder_.getMessageList();
}
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public int getPointDataCount() {
if (pointDataBuilder_ == null) {
return pointData_.size();
} else {
return pointDataBuilder_.getCount();
}
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public com.google.monitoring.v3.TimeSeriesData.PointData getPointData(int index) {
if (pointDataBuilder_ == null) {
return pointData_.get(index);
} else {
return pointDataBuilder_.getMessage(index);
}
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public Builder setPointData(
int index, com.google.monitoring.v3.TimeSeriesData.PointData value) {
if (pointDataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePointDataIsMutable();
pointData_.set(index, value);
onChanged();
} else {
pointDataBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public Builder setPointData(
int index, com.google.monitoring.v3.TimeSeriesData.PointData.Builder builderForValue) {
if (pointDataBuilder_ == null) {
ensurePointDataIsMutable();
pointData_.set(index, builderForValue.build());
onChanged();
} else {
pointDataBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public Builder addPointData(com.google.monitoring.v3.TimeSeriesData.PointData value) {
if (pointDataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePointDataIsMutable();
pointData_.add(value);
onChanged();
} else {
pointDataBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public Builder addPointData(
int index, com.google.monitoring.v3.TimeSeriesData.PointData value) {
if (pointDataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePointDataIsMutable();
pointData_.add(index, value);
onChanged();
} else {
pointDataBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public Builder addPointData(
com.google.monitoring.v3.TimeSeriesData.PointData.Builder builderForValue) {
if (pointDataBuilder_ == null) {
ensurePointDataIsMutable();
pointData_.add(builderForValue.build());
onChanged();
} else {
pointDataBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public Builder addPointData(
int index, com.google.monitoring.v3.TimeSeriesData.PointData.Builder builderForValue) {
if (pointDataBuilder_ == null) {
ensurePointDataIsMutable();
pointData_.add(index, builderForValue.build());
onChanged();
} else {
pointDataBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public Builder addAllPointData(
java.lang.Iterable<? extends com.google.monitoring.v3.TimeSeriesData.PointData> values) {
if (pointDataBuilder_ == null) {
ensurePointDataIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, pointData_);
onChanged();
} else {
pointDataBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public Builder clearPointData() {
if (pointDataBuilder_ == null) {
pointData_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
} else {
pointDataBuilder_.clear();
}
return this;
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public Builder removePointData(int index) {
if (pointDataBuilder_ == null) {
ensurePointDataIsMutable();
pointData_.remove(index);
onChanged();
} else {
pointDataBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public com.google.monitoring.v3.TimeSeriesData.PointData.Builder getPointDataBuilder(
int index) {
return getPointDataFieldBuilder().getBuilder(index);
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public com.google.monitoring.v3.TimeSeriesData.PointDataOrBuilder getPointDataOrBuilder(
int index) {
if (pointDataBuilder_ == null) {
return pointData_.get(index); } else {
return pointDataBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public java.util.List<? extends com.google.monitoring.v3.TimeSeriesData.PointDataOrBuilder>
getPointDataOrBuilderList() {
if (pointDataBuilder_ != null) {
return pointDataBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(pointData_);
}
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public com.google.monitoring.v3.TimeSeriesData.PointData.Builder addPointDataBuilder() {
return getPointDataFieldBuilder().addBuilder(
com.google.monitoring.v3.TimeSeriesData.PointData.getDefaultInstance());
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public com.google.monitoring.v3.TimeSeriesData.PointData.Builder addPointDataBuilder(
int index) {
return getPointDataFieldBuilder().addBuilder(
index, com.google.monitoring.v3.TimeSeriesData.PointData.getDefaultInstance());
}
/**
* <pre>
* The points in the time series.
* </pre>
*
* <code>repeated .google.monitoring.v3.TimeSeriesData.PointData point_data = 2;</code>
*/
public java.util.List<com.google.monitoring.v3.TimeSeriesData.PointData.Builder>
getPointDataBuilderList() {
return getPointDataFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.monitoring.v3.TimeSeriesData.PointData, com.google.monitoring.v3.TimeSeriesData.PointData.Builder, com.google.monitoring.v3.TimeSeriesData.PointDataOrBuilder>
getPointDataFieldBuilder() {
if (pointDataBuilder_ == null) {
pointDataBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.monitoring.v3.TimeSeriesData.PointData, com.google.monitoring.v3.TimeSeriesData.PointData.Builder, com.google.monitoring.v3.TimeSeriesData.PointDataOrBuilder>(
pointData_,
((bitField0_ & 0x00000002) != 0),
getParentForChildren(),
isClean());
pointData_ = null;
}
return pointDataBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.monitoring.v3.TimeSeriesData)
}
// @@protoc_insertion_point(class_scope:google.monitoring.v3.TimeSeriesData)
private static final com.google.monitoring.v3.TimeSeriesData DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.monitoring.v3.TimeSeriesData();
}
public static com.google.monitoring.v3.TimeSeriesData getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<TimeSeriesData>
PARSER = new com.google.protobuf.AbstractParser<TimeSeriesData>() {
@java.lang.Override
public TimeSeriesData parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new TimeSeriesData(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<TimeSeriesData> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<TimeSeriesData> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.monitoring.v3.TimeSeriesData getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| 35.247073 | 196 | 0.641983 |
9e51a0886666a4fb52440db85be2dbe5d847caf4 | 1,400 | package com.github.nkolytschew1.aws.core.config.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
/**
* @author NKO
* @version %I%, %G%
* @since 1.0.0-SNAPSHOT
*/
@Configuration
@Order
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
protected OAuth2RestTemplate getOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) {
return new OAuth2RestTemplate(resource, context);
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/index.html", "/home", "/").permitAll()
.anyRequest().authenticated()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
// @formatter:on
}
} | 35.897436 | 123 | 0.800714 |
1b860d6fc4401c141420cea99e2e7b66eab9863a | 184 | /**
* Redis specific query execution engine.
*/
@org.springframework.lang.NonNullApi
@org.springframework.lang.NonNullFields
package org.springframework.data.redis.repository.query;
| 26.285714 | 56 | 0.809783 |
107403c06c2b857bb9e80387af15151d033a756c | 26,823 | package com.asura.agent.entity;
/**
* <p></p>
* <p/>
* <PRE>
* <BR>
* <BR>-----------------------------------------------
* <BR>
* </PRE>
*
* @author zhaozq14
* @version 1.0
* @date 2016-09-15 22:44:11
* @since 1.0
*/
public class MonitorConfigureEntity {
/**
* This field corresponds to the database column monitor_configure.configure_id
* Comment:
* @param configureId the value for monitor_configure.configure_id
*/
private Integer configureId;
/**
* This field corresponds to the database column monitor_configure.host_id
* Comment: 主机,参考资源server_id
* @param hostId the value for monitor_configure.host_id
*/
private Integer hostId;
/**
* This field corresponds to the database column monitor_configure.description
* Comment: 描述信息
* @param description the value for monitor_configure.description
*/
private String description;
/**
* This field corresponds to the database column monitor_configure.monitor_time
* Comment:
* @param monitorTime the value for monitor_configure.monitor_time
*/
private String monitorTime;
/**
* This field corresponds to the database column monitor_configure.alarm_count
* Comment: 报警次数
* @param alarmCount the value for monitor_configure.alarm_count
*/
private Integer alarmCount;
/**
* This field corresponds to the database column monitor_configure.alarm_interval
* Comment: 报警间隔
* @param alarmInterval the value for monitor_configure.alarm_interval
*/
private Integer alarmInterval;
/**
* This field corresponds to the database column monitor_configure.script_id
* Comment: 脚本名,参考脚本id
* @param scriptId the value for monitor_configure.script_id
*/
private Integer scriptId;
/**
* This field corresponds to the database column monitor_configure.is_valid
* Comment: 是否有效
* @param isValid the value for monitor_configure.is_valid
*/
private Integer isValid;
/**
* This field corresponds to the database column monitor_configure.last_modify_time
* Comment: 最近修改时间
* @param lastModifyTime the value for monitor_configure.last_modify_time
*/
private java.sql.Timestamp lastModifyTime;
/**
* This field corresponds to the database column monitor_configure.last_modify_user
* Comment: 最近修改人
* @param lastModifyUser the value for monitor_configure.last_modify_user
*/
private String lastModifyUser;
/**
* This field corresponds to the database column monitor_configure.template_id
* Comment: 使用模板,可以使用多个用逗号分隔
* @param templateId the value for monitor_configure.template_id
*/
private String templateId;
/**
* This field corresponds to the database column monitor_configure.groups_id
* Comment: 使用组,多个用逗号分隔
* @param groupsId the value for monitor_configure.groups_id
*/
private String groupsId;
/**
* This field corresponds to the database column monitor_configure.retry
* Comment: 失败重试次数
* @param retry the value for monitor_configure.retry
*/
private Integer retry;
/**
* This field corresponds to the database column monitor_configure.monitor_configure_tp
* Comment:
* @param monitorConfigureTp the value for monitor_configure.monitor_configure_tp
*/
private String monitorConfigureTp;
/**
* This field corresponds to the database column monitor_configure.monitor_hosts_tp
* Comment:
* @param monitorHostsTp the value for monitor_configure.monitor_hosts_tp
*/
private String monitorHostsTp;
/**
* This field corresponds to the database column monitor_configure.hosts
* Comment: 监控服务器IP地址,参考cmdb的server_id
* @param hosts the value for monitor_configure.hosts
*/
private String hosts;
/**
* This field corresponds to the database column monitor_configure.arg1
* Comment: 参数1
* @param arg1 the value for monitor_configure.arg1
*/
private String arg1;
/**
* This field corresponds to the database column monitor_configure.arg2
* Comment: 参数2
* @param arg2 the value for monitor_configure.arg2
*/
private String arg2;
/**
* This field corresponds to the database column monitor_configure.arg3
* Comment: 参数3
* @param arg3 the value for monitor_configure.arg3
*/
private String arg3;
/**
* This field corresponds to the database column monitor_configure.arg4
* Comment: 参数4
* @param arg4 the value for monitor_configure.arg4
*/
private String arg4;
/**
* This field corresponds to the database column monitor_configure.arg5
* Comment: 参数5
* @param arg5 the value for monitor_configure.arg5
*/
private String arg5;
/**
* This field corresponds to the database column monitor_configure.arg6
* Comment: 参数6
* @param arg6 the value for monitor_configure.arg6
*/
private String arg6;
/**
* This field corresponds to the database column monitor_configure.arg7
* Comment: 参数7
* @param arg7 the value for monitor_configure.arg7
*/
private String arg7;
/**
* This field corresponds to the database column monitor_configure.arg8
* Comment: 参数8
* @param arg8 the value for monitor_configure.arg8
*/
private String arg8;
/**
* This field corresponds to the database column monitor_configure.check_interval
* Comment: 脚本检查间隔
* @param checkInterval the value for monitor_configure.check_interval
*/
private Integer checkInterval;
/**
* This field corresponds to the database column monitor_configure.is_mobile
* Comment: 报警发送给手机,1有效,0无效
* @param isMobile the value for monitor_configure.is_mobile
*/
private Integer isMobile;
/**
* This field corresponds to the database column monitor_configure.is_email
* Comment: 报警发送给手机,1有效,0无效
* @param isEmail the value for monitor_configure.is_email
*/
private Integer isEmail;
/**
* This field corresponds to the database column monitor_configure.is_ding
* Comment: 报警发送给钉钉,1有效,0无效
* @param isDing the value for monitor_configure.is_ding
*/
private Integer isDing;
/**
* This field corresponds to the database column monitor_configure.is_weixin
* Comment: 报警发送给微信,1有效,0无效
* @param isWeixin the value for monitor_configure.is_weixin
*/
private Integer isWeixin;
/**
* This field corresponds to the database column monitor_configure.weixin_groups
* Comment:
* @param weixinGroups the value for monitor_configure.weixin_groups
*/
private String weixinGroups;
/**
* This field corresponds to the database column monitor_configure.ding_groups
* Comment:
* @param dingGroups the value for monitor_configure.ding_groups
*/
private String dingGroups;
/**
* This field corresponds to the database column monitor_configure.mobile_groups
* Comment:
* @param mobileGroups the value for monitor_configure.mobile_groups
*/
private String mobileGroups;
/**
* This field corresponds to the database column monitor_configure.email_groups
* Comment:
* @param emailGroups the value for monitor_configure.email_groups
*/
private String emailGroups;
/**
* This field corresponds to the database column monitor_configure.all_groups
* Comment:
* @param allGroups the value for monitor_configure.all_groups
*/
private String allGroups;
/**
* This field corresponds to the database column monitor_configure.item_id
* Comment: 项目id,参考监控项目的id
* @param itemId the value for monitor_configure.item_id
*/
private String itemId;
/**
* This field corresponds to the database column monitor_configure.gname
* Comment:
* @param gname the value for monitor_configure.gname
*/
private String gname;
/**
* This field corresponds to the database column monitor_configure.configure_id
* Comment:
* @param configureId the value for monitor_configure.configure_id
*/
public void setConfigureId(Integer configureId){
this.configureId = configureId;
}
/**
* This field corresponds to the database column monitor_configure.host_id
* Comment: 主机,参考资源server_id
* @param hostId the value for monitor_configure.host_id
*/
public void setHostId(Integer hostId){
this.hostId = hostId;
}
/**
* This field corresponds to the database column monitor_configure.description
* Comment: 描述信息
* @param description the value for monitor_configure.description
*/
public void setDescription(String description){
this.description = description;
}
/**
* This field corresponds to the database column monitor_configure.monitor_time
* Comment:
* @param monitorTime the value for monitor_configure.monitor_time
*/
public void setMonitorTime(String monitorTime){
this.monitorTime = monitorTime;
}
/**
* This field corresponds to the database column monitor_configure.alarm_count
* Comment: 报警次数
* @param alarmCount the value for monitor_configure.alarm_count
*/
public void setAlarmCount(Integer alarmCount){
this.alarmCount = alarmCount;
}
/**
* This field corresponds to the database column monitor_configure.alarm_interval
* Comment: 报警间隔
* @param alarmInterval the value for monitor_configure.alarm_interval
*/
public void setAlarmInterval(Integer alarmInterval){
this.alarmInterval = alarmInterval;
}
/**
* This field corresponds to the database column monitor_configure.script_id
* Comment: 脚本名,参考脚本id
* @param scriptId the value for monitor_configure.script_id
*/
public void setScriptId(Integer scriptId){
this.scriptId = scriptId;
}
/**
* This field corresponds to the database column monitor_configure.is_valid
* Comment: 是否有效
* @param isValid the value for monitor_configure.is_valid
*/
public void setIsValid(Integer isValid){
this.isValid = isValid;
}
/**
* This field corresponds to the database column monitor_configure.last_modify_time
* Comment: 最近修改时间
* @param lastModifyTime the value for monitor_configure.last_modify_time
*/
public void setLastModifyTime(java.sql.Timestamp lastModifyTime){
this.lastModifyTime = lastModifyTime;
}
/**
* This field corresponds to the database column monitor_configure.last_modify_user
* Comment: 最近修改人
* @param lastModifyUser the value for monitor_configure.last_modify_user
*/
public void setLastModifyUser(String lastModifyUser){
this.lastModifyUser = lastModifyUser;
}
/**
* This field corresponds to the database column monitor_configure.template_id
* Comment: 使用模板,可以使用多个用逗号分隔
* @param templateId the value for monitor_configure.template_id
*/
public void setTemplateId(String templateId){
this.templateId = templateId;
}
/**
* This field corresponds to the database column monitor_configure.groups_id
* Comment: 使用组,多个用逗号分隔
* @param groupsId the value for monitor_configure.groups_id
*/
public void setGroupsId(String groupsId){
this.groupsId = groupsId;
}
/**
* This field corresponds to the database column monitor_configure.retry
* Comment: 失败重试次数
* @param retry the value for monitor_configure.retry
*/
public void setRetry(Integer retry){
this.retry = retry;
}
/**
* This field corresponds to the database column monitor_configure.monitor_configure_tp
* Comment:
* @param monitorConfigureTp the value for monitor_configure.monitor_configure_tp
*/
public void setMonitorConfigureTp(String monitorConfigureTp){
this.monitorConfigureTp = monitorConfigureTp;
}
/**
* This field corresponds to the database column monitor_configure.monitor_hosts_tp
* Comment:
* @param monitorHostsTp the value for monitor_configure.monitor_hosts_tp
*/
public void setMonitorHostsTp(String monitorHostsTp){
this.monitorHostsTp = monitorHostsTp;
}
/**
* This field corresponds to the database column monitor_configure.hosts
* Comment: 监控服务器IP地址,参考cmdb的server_id
* @param hosts the value for monitor_configure.hosts
*/
public void setHosts(String hosts){
this.hosts = hosts;
}
/**
* This field corresponds to the database column monitor_configure.arg1
* Comment: 参数1
* @param arg1 the value for monitor_configure.arg1
*/
public void setArg1(String arg1){
this.arg1 = arg1;
}
/**
* This field corresponds to the database column monitor_configure.arg2
* Comment: 参数2
* @param arg2 the value for monitor_configure.arg2
*/
public void setArg2(String arg2){
this.arg2 = arg2;
}
/**
* This field corresponds to the database column monitor_configure.arg3
* Comment: 参数3
* @param arg3 the value for monitor_configure.arg3
*/
public void setArg3(String arg3){
this.arg3 = arg3;
}
/**
* This field corresponds to the database column monitor_configure.arg4
* Comment: 参数4
* @param arg4 the value for monitor_configure.arg4
*/
public void setArg4(String arg4){
this.arg4 = arg4;
}
/**
* This field corresponds to the database column monitor_configure.arg5
* Comment: 参数5
* @param arg5 the value for monitor_configure.arg5
*/
public void setArg5(String arg5){
this.arg5 = arg5;
}
/**
* This field corresponds to the database column monitor_configure.arg6
* Comment: 参数6
* @param arg6 the value for monitor_configure.arg6
*/
public void setArg6(String arg6){
this.arg6 = arg6;
}
/**
* This field corresponds to the database column monitor_configure.arg7
* Comment: 参数7
* @param arg7 the value for monitor_configure.arg7
*/
public void setArg7(String arg7){
this.arg7 = arg7;
}
/**
* This field corresponds to the database column monitor_configure.arg8
* Comment: 参数8
* @param arg8 the value for monitor_configure.arg8
*/
public void setArg8(String arg8){
this.arg8 = arg8;
}
/**
* This field corresponds to the database column monitor_configure.check_interval
* Comment: 脚本检查间隔
* @param checkInterval the value for monitor_configure.check_interval
*/
public void setCheckInterval(Integer checkInterval){
this.checkInterval = checkInterval;
}
/**
* This field corresponds to the database column monitor_configure.is_mobile
* Comment: 报警发送给手机,1有效,0无效
* @param isMobile the value for monitor_configure.is_mobile
*/
public void setIsMobile(Integer isMobile){
this.isMobile = isMobile;
}
/**
* This field corresponds to the database column monitor_configure.is_email
* Comment: 报警发送给手机,1有效,0无效
* @param isEmail the value for monitor_configure.is_email
*/
public void setIsEmail(Integer isEmail){
this.isEmail = isEmail;
}
/**
* This field corresponds to the database column monitor_configure.is_ding
* Comment: 报警发送给钉钉,1有效,0无效
* @param isDing the value for monitor_configure.is_ding
*/
public void setIsDing(Integer isDing){
this.isDing = isDing;
}
/**
* This field corresponds to the database column monitor_configure.is_weixin
* Comment: 报警发送给微信,1有效,0无效
* @param isWeixin the value for monitor_configure.is_weixin
*/
public void setIsWeixin(Integer isWeixin){
this.isWeixin = isWeixin;
}
/**
* This field corresponds to the database column monitor_configure.weixin_groups
* Comment:
* @param weixinGroups the value for monitor_configure.weixin_groups
*/
public void setWeixinGroups(String weixinGroups){
this.weixinGroups = weixinGroups;
}
/**
* This field corresponds to the database column monitor_configure.ding_groups
* Comment:
* @param dingGroups the value for monitor_configure.ding_groups
*/
public void setDingGroups(String dingGroups){
this.dingGroups = dingGroups;
}
/**
* This field corresponds to the database column monitor_configure.mobile_groups
* Comment:
* @param mobileGroups the value for monitor_configure.mobile_groups
*/
public void setMobileGroups(String mobileGroups){
this.mobileGroups = mobileGroups;
}
/**
* This field corresponds to the database column monitor_configure.email_groups
* Comment:
* @param emailGroups the value for monitor_configure.email_groups
*/
public void setEmailGroups(String emailGroups){
this.emailGroups = emailGroups;
}
/**
* This field corresponds to the database column monitor_configure.all_groups
* Comment:
* @param allGroups the value for monitor_configure.all_groups
*/
public void setAllGroups(String allGroups){
this.allGroups = allGroups;
}
/**
* This field corresponds to the database column monitor_configure.item_id
* Comment: 项目id,参考监控项目的id
* @param itemId the value for monitor_configure.item_id
*/
public void setItemId(String itemId){
this.itemId = itemId;
}
/**
* This field corresponds to the database column monitor_configure.gname
* Comment:
* @param gname the value for monitor_configure.gname
*/
public void setGname(String gname){
this.gname = gname;
}
/**
* This field corresponds to the database column monitor_configure.configure_id
* Comment:
* @return the value of monitor_configure.configure_id
*/
public Integer getConfigureId() {
return configureId;
}
/**
* This field corresponds to the database column monitor_configure.host_id
* Comment: 主机,参考资源server_id
* @return the value of monitor_configure.host_id
*/
public Integer getHostId() {
return hostId;
}
/**
* This field corresponds to the database column monitor_configure.description
* Comment: 描述信息
* @return the value of monitor_configure.description
*/
public String getDescription() {
return description;
}
/**
* This field corresponds to the database column monitor_configure.monitor_time
* Comment:
* @return the value of monitor_configure.monitor_time
*/
public String getMonitorTime() {
return monitorTime;
}
/**
* This field corresponds to the database column monitor_configure.alarm_count
* Comment: 报警次数
* @return the value of monitor_configure.alarm_count
*/
public Integer getAlarmCount() {
return alarmCount;
}
/**
* This field corresponds to the database column monitor_configure.alarm_interval
* Comment: 报警间隔
* @return the value of monitor_configure.alarm_interval
*/
public Integer getAlarmInterval() {
return alarmInterval;
}
/**
* This field corresponds to the database column monitor_configure.script_id
* Comment: 脚本名,参考脚本id
* @return the value of monitor_configure.script_id
*/
public Integer getScriptId() {
return scriptId;
}
/**
* This field corresponds to the database column monitor_configure.is_valid
* Comment: 是否有效
* @return the value of monitor_configure.is_valid
*/
public Integer getIsValid() {
return isValid;
}
/**
* This field corresponds to the database column monitor_configure.last_modify_time
* Comment: 最近修改时间
* @return the value of monitor_configure.last_modify_time
*/
public java.sql.Timestamp getLastModifyTime() {
return lastModifyTime;
}
/**
* This field corresponds to the database column monitor_configure.last_modify_user
* Comment: 最近修改人
* @return the value of monitor_configure.last_modify_user
*/
public String getLastModifyUser() {
return lastModifyUser;
}
/**
* This field corresponds to the database column monitor_configure.template_id
* Comment: 使用模板,可以使用多个用逗号分隔
* @return the value of monitor_configure.template_id
*/
public String getTemplateId() {
return templateId;
}
/**
* This field corresponds to the database column monitor_configure.groups_id
* Comment: 使用组,多个用逗号分隔
* @return the value of monitor_configure.groups_id
*/
public String getGroupsId() {
return groupsId;
}
/**
* This field corresponds to the database column monitor_configure.retry
* Comment: 失败重试次数
* @return the value of monitor_configure.retry
*/
public Integer getRetry() {
return retry;
}
/**
* This field corresponds to the database column monitor_configure.monitor_configure_tp
* Comment:
* @return the value of monitor_configure.monitor_configure_tp
*/
public String getMonitorConfigureTp() {
return monitorConfigureTp;
}
/**
* This field corresponds to the database column monitor_configure.monitor_hosts_tp
* Comment:
* @return the value of monitor_configure.monitor_hosts_tp
*/
public String getMonitorHostsTp() {
return monitorHostsTp;
}
/**
* This field corresponds to the database column monitor_configure.hosts
* Comment: 监控服务器IP地址,参考cmdb的server_id
* @return the value of monitor_configure.hosts
*/
public String getHosts() {
return hosts;
}
/**
* This field corresponds to the database column monitor_configure.arg1
* Comment: 参数1
* @return the value of monitor_configure.arg1
*/
public String getArg1() {
return arg1;
}
/**
* This field corresponds to the database column monitor_configure.arg2
* Comment: 参数2
* @return the value of monitor_configure.arg2
*/
public String getArg2() {
return arg2;
}
/**
* This field corresponds to the database column monitor_configure.arg3
* Comment: 参数3
* @return the value of monitor_configure.arg3
*/
public String getArg3() {
return arg3;
}
/**
* This field corresponds to the database column monitor_configure.arg4
* Comment: 参数4
* @return the value of monitor_configure.arg4
*/
public String getArg4() {
return arg4;
}
/**
* This field corresponds to the database column monitor_configure.arg5
* Comment: 参数5
* @return the value of monitor_configure.arg5
*/
public String getArg5() {
return arg5;
}
/**
* This field corresponds to the database column monitor_configure.arg6
* Comment: 参数6
* @return the value of monitor_configure.arg6
*/
public String getArg6() {
return arg6;
}
/**
* This field corresponds to the database column monitor_configure.arg7
* Comment: 参数7
* @return the value of monitor_configure.arg7
*/
public String getArg7() {
return arg7;
}
/**
* This field corresponds to the database column monitor_configure.arg8
* Comment: 参数8
* @return the value of monitor_configure.arg8
*/
public String getArg8() {
return arg8;
}
/**
* This field corresponds to the database column monitor_configure.check_interval
* Comment: 脚本检查间隔
* @return the value of monitor_configure.check_interval
*/
public Integer getCheckInterval() {
return checkInterval;
}
/**
* This field corresponds to the database column monitor_configure.is_mobile
* Comment: 报警发送给手机,1有效,0无效
* @return the value of monitor_configure.is_mobile
*/
public Integer getIsMobile() {
return isMobile;
}
/**
* This field corresponds to the database column monitor_configure.is_email
* Comment: 报警发送给手机,1有效,0无效
* @return the value of monitor_configure.is_email
*/
public Integer getIsEmail() {
return isEmail;
}
/**
* This field corresponds to the database column monitor_configure.is_ding
* Comment: 报警发送给钉钉,1有效,0无效
* @return the value of monitor_configure.is_ding
*/
public Integer getIsDing() {
return isDing;
}
/**
* This field corresponds to the database column monitor_configure.is_weixin
* Comment: 报警发送给微信,1有效,0无效
* @return the value of monitor_configure.is_weixin
*/
public Integer getIsWeixin() {
return isWeixin;
}
/**
* This field corresponds to the database column monitor_configure.weixin_groups
* Comment:
* @return the value of monitor_configure.weixin_groups
*/
public String getWeixinGroups() {
return weixinGroups;
}
/**
* This field corresponds to the database column monitor_configure.ding_groups
* Comment:
* @return the value of monitor_configure.ding_groups
*/
public String getDingGroups() {
return dingGroups;
}
/**
* This field corresponds to the database column monitor_configure.mobile_groups
* Comment:
* @return the value of monitor_configure.mobile_groups
*/
public String getMobileGroups() {
return mobileGroups;
}
/**
* This field corresponds to the database column monitor_configure.email_groups
* Comment:
* @return the value of monitor_configure.email_groups
*/
public String getEmailGroups() {
return emailGroups;
}
/**
* This field corresponds to the database column monitor_configure.all_groups
* Comment:
* @return the value of monitor_configure.all_groups
*/
public String getAllGroups() {
return allGroups;
}
/**
* This field corresponds to the database column monitor_configure.item_id
* Comment: 项目id,参考监控项目的id
* @return the value of monitor_configure.item_id
*/
public String getItemId() {
return itemId;
}
/**
* This field corresponds to the database column monitor_configure.gname
* Comment:
* @return the value of monitor_configure.gname
*/
public String getGname() {
return gname;
}
}
| 27.066599 | 91 | 0.668904 |
acc6ddd4c2fcdc98957c62ec60b65eb972461c22 | 3,745 | package XMLScanner;
import org.codice.testify.objects.*;
import org.codice.testify.testParsers.TestParser;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Hashtable;
import java.util.Scanner;
/**
* The XMLScannerTestParser class is a Testify TestParser service for extension type xml
*/
public class XMLScannerTestParser implements BundleActivator, TestParser {
@Override
public ParsedData parseTest(File file) {
TestifyLogger.debug("Running XMLScannerTestParser", this.getClass().getSimpleName());
//Scan the file into a String
String testString = null;
try {
Scanner scanner = new Scanner(file);
testString = scanner.useDelimiter("\\Z").next();
scanner.close();
} catch (FileNotFoundException e) {
TestifyLogger.error(e.getMessage(), this.getClass().getSimpleName());
}
//If the test file string is null, set parsed data to null
if (testString == null) {
return null;
//If test file string contains certain key words for this parser, then parse the string
} else if (testString.contains("<type>") && testString.contains("<endpoint>") && testString.contains("<test>") && testString.contains("<assertion>")) {
String type = testString.substring(testString.indexOf("<type>") + 6, testString.indexOf("</type>")).trim();
String endpoint = testString.substring(testString.indexOf("<endpoint>") + 10, testString.indexOf("</endpoint>")).trim();
String test = testString.substring(testString.indexOf("<test>") + 6, testString.indexOf("</test>")).trim();
String assertion = testString.substring(testString.indexOf("<assertion>") + 11, testString.indexOf("</assertion>")).trim();
String preTestSetterAction = null;
if (testString.contains("<preTestSetterAction>")) {
preTestSetterAction = testString.substring(testString.indexOf("<preTestSetterAction>") + 21, testString.indexOf("</preTestSetterAction>")).trim();
}
String preTestProcessorAction = null;
if (testString.contains("<preTestProcessorAction>")) {
preTestProcessorAction = testString.substring(testString.indexOf("<preTestProcessorAction>") + 24, testString.indexOf("</preTestProcessorAction>")).trim();
}
String postTestProcessorAction = null;
if (testString.contains("<postTestProcessorAction>")) {
postTestProcessorAction = testString.substring(testString.indexOf("<postTestProcessorAction>") + 25, testString.indexOf("</postTestProcessorAction>")).trim();
}
//Store the request, assertion, and action data in the parsed data object
Request request = new Request(type, endpoint, test);
ActionData actionData = new ActionData(preTestSetterAction, preTestProcessorAction, postTestProcessorAction);
return new ParsedData(request, assertion, actionData);
//If the test file string does not contain certain key words, set parsed data to null
} else {
return null;
}
}
@Override
public void start(BundleContext bundleContext) throws Exception {
//Register the TestParser service for extension xml
Hashtable<String, String> extension = new Hashtable<>();
extension.put("extension", "xml");
bundleContext.registerService(TestParser.class.getName(), new XMLScannerTestParser(), extension);
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
}
}
| 44.058824 | 174 | 0.669426 |
28b88ed02111494118a458edcb92e3e08ffc1b8f | 978 | package domain;
import com.google.gson.annotations.Expose;
import java.util.LinkedList;
import java.util.List;
public class Administrators{
@Expose private final List<String> administrators;
@Expose private final Campus campus;
public Administrators(Campus campus){
this.campus = campus;
administrators = new LinkedList<>();
initAdminID();
}
private void initAdminID() {
for (int i = 1111; i < 10000; i *= 2) administrators.add(campus.abrev.toLowerCase() + "a" + i);
}
/**
* Check admin id
* @param fullID full admin id
* @return boolean
*/
public boolean contains(String fullID){
fullID = fullID.toLowerCase();
System.out.println(fullID);
for(String id : administrators){
System.out.println(id);
if(id.equals(fullID)) return true;
}
return false;
}
public int size(){
return administrators.size();
}
}
| 23.853659 | 103 | 0.611452 |
c183e41e7d651402d3cbf0888f8b703f52dc9247 | 2,424 | package com.communote.server.core.blog;
import com.communote.server.api.core.event.Event;
/**
* @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a>
*/
public class TopicHierarchyEvent implements Event {
/**
* Possible types this event was fired for.
*/
public enum Type {
/** A connection between topics was added. */
ADD,
/** A connection between topics was removed */
REMOVE
}
/**
* default serial version UID
*/
private static final long serialVersionUID = 1L;
private final Long parentTopicId;
private final String parentTopicTitle;
private final Long childTopicId;
private final String childTopicTitle;
private final Long userId;
private final Type type;
/**
* Constructor.
*
* @param parentTopicId
* Id of the parent topic.
* @param parentTopicTitle
* title of the parent topic
* @param childTopicId
* Id of the child topic.
* @param childTopicTitle
* title of the child topic
* @param userId
* Id of the invoking user.
* @param type
* Type of the event.
*/
public TopicHierarchyEvent(Long parentTopicId, String parentTopicTitle, Long childTopicId,
String childTopicTitle, Long userId, Type type) {
this.parentTopicId = parentTopicId;
this.parentTopicTitle = parentTopicTitle;
this.childTopicId = childTopicId;
this.childTopicTitle = childTopicTitle;
this.userId = userId;
this.type = type;
}
/**
* @return Id of the affected child.
*/
public Long getChildTopicId() {
return childTopicId;
}
/**
* @return the title of the child topic
*/
public String getChildTopicTitle() {
return childTopicTitle;
}
/**
* @return Id of the affected parent.
*/
public Long getParentTopicId() {
return parentTopicId;
}
/**
* @return the title of the parent topic
*/
public String getParentTopicTitle() {
return parentTopicTitle;
}
/**
* @return Type of this event.
*/
public Type getType() {
return type;
}
/**
* @return Id of the invoking user.
*/
public Long getUserId() {
return userId;
}
}
| 24.484848 | 94 | 0.590759 |
e7109da8ff97501aba1f62bb28859dcfe1e45994 | 1,211 | package com.arslinthboot.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.*;
import lombok.experimental.SuperBuilder;
import java.util.Date;
/**
* @author Arslinth
* @ClassName SysJobLog
* @Description 定时任务调度日志表
* @Date 2022/5/3
*/
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class SysJobLog extends BaseEntity {
/**
* ID主键
*/
@TableId(type = IdType.ASSIGN_ID)
private String id;
/**
* 关联任务id
*/
private String jobId;
/**
* 任务名称
*/
private String jobName;
/**
* 任务组名
*/
private String jobGroup;
/**
* 调用目标字符串
*/
private String invokeTarget;
/**
* 日志信息
*/
private String jobMessage;
/**
* 执行状态(true正常 false异常)
*/
private Boolean status;
/**
* 异常信息
*/
private String exceptionInfo;
/**
* 开始时间
*/
@TableField(exist = false)
private Date startTime;
/**
* 停止时间
*/
@TableField(exist = false)
private Date stopTime;
}
| 15.727273 | 54 | 0.612717 |
fc76129339cdab4ce24cd63bd10d3acb868e96df | 899 | package com.pattern.proxy.dynamicproxy.jdkproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author healk
*/
public class JdkProxy implements InvocationHandler {
private Object target;
/**
* 拿到目标对象
* @param obj
* @return
*/
public Object getInstance(Object obj){
this.target = obj;
Class<?> clazz = target.getClass();
return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
Object result = method.invoke(this.target, args);
after();
return result;
}
private void after() {
System.out.println("完成订单");
}
private void before() {
System.out.println("跑腿,接收等订单");
}
}
| 22.475 | 89 | 0.632925 |
d13f6a8a82e6c3bde21aa94e40a80dda582605cd | 2,386 | package org.crazyit.myphoneassistant.common.rx.subscriber;
import android.content.Context;
import org.crazyit.myphoneassistant.common.util.ProgressDialogHandler;
import io.reactivex.disposables.Disposable;
/**
* Created by Administrator on 2018/6/12.
*/
//因为这个地方我们没有实现onNext这个方法所以我们将这个类定义为了abstract抽象类.
public abstract class ProgressDialogSubscriber<T> extends ErrorHandlerSubscriber<T> implements ProgressDialogHandler.OnProgressCancelListener {
////
private ProgressDialogHandler mProgressDialogHandler;
private Disposable mDisposable;
/////
public ProgressDialogSubscriber(Context context){
super(context);
mProgressDialogHandler=new ProgressDialogHandler(mContext,true,this);
}
protected boolean isShowProgressDialog(){
return true;
}
@Override
public void onCancelProgress() {
//这样便是取消订阅
mDisposable.dispose();
}
// private Context mContext;
// private BaseView baseView;
// private ProgressDialog progressDialog;
// public ProgressDialogSubscriber(BaseView view, RxErrorHandler rxErrorHandler) {
// super(rxErrorHandler);
// this.baseView=view;
// }
@Override
public void onSubscribe(Disposable d) {
mDisposable=d;
if (isShowProgressDialog()){
this.mProgressDialogHandler.showProgressDialog();
}
}
@Override
public void onComplete() {
if (isShowProgressDialog()){
this.mProgressDialogHandler.dismissProgressDialog();
}
}
@Override
public void onError(Throwable e) {
super.onError(e);
if (isShowProgressDialog()) {
this.mProgressDialogHandler.dismissProgressDialog();
}
}
// private void initProgressDialog(){
// if (progressDialog==null){
// //通过构造方法来获取到这个context
// progressDialog=new ProgressDialog(mContext);
// progressDialog.setMessage("loading ............");
// }
// }
// private void showProgressDialog(){
//// initProgressDialog();
//// progressDialog.show();
// baseView.showLoading();
//
// }
// private void dismissProgressDialog(){
//
//// if (progressDialog!=null&&progressDialog.isShowing()){
//// progressDialog.dismiss();
//// }
// baseView.dimissLoading();
// }
}
| 24.854167 | 144 | 0.64627 |
3737c8245ea5961de989cb2a516d5cbdf82b2f28 | 1,482 | package com.leetcode.stock.one;
/**
*
* 198. 打家劫舍
*
* 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
*
* 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。
*
* 示例 1:
*
* 输入: [1,2,3,1]
* 输出: 4
* 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
* 偷窃到的最高金额 = 1 + 3 = 4 。
* 示例 2:
*
* 输入: [2,7,9,3,1]
* 输出: 12
* 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
* 偷窃到的最高金额 = 2 + 9 + 1 = 12 。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/house-robber
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* @author Mr.F
* @since 2019/11/20 16:11
**/
public class LeetCode198 {
public static void main(String[] args) {
LeetCode198 obj = new LeetCode198();
System.out.println(obj.rob1(new int[]{2,1,1,2}));
}
// 动态规划
public int rob(int[] nums) {
int prevMax = 0;
int currMax = 0;
for (int x : nums) {
int temp = currMax;
currMax = Math.max(prevMax + x, currMax);
prevMax = temp;
}
return currMax;
}
// 动态规划
// dp[n] = MAX( dp[n-1], dp[n-2] + num )
public int rob1(int[] nums) {
int len = nums.length;
if(len == 0)
return 0;
int[] dp = new int[len + 1];
dp[0] = 0;
dp[1] = nums[0];
for(int i = 2; i <= len; i++) {
dp[i] = Math.max(dp[i-1], dp[i-2] + nums[i-1]);
}
return dp[len];
}
}
| 22.8 | 95 | 0.510796 |
4a112d59cc4f2b3365793644cdbc55607487fbd3 | 1,413 | /*
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.sun.xml.ws.security;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.SecretKey;
/**
* DerivedKeyToken Interface
* TODO: This defintion is incomplete. Currently it has only those members which are required
* for the Trust Interop Scenarios
*/
public interface DerivedKeyToken extends Token {
public static final String DERIVED_KEY_TOKEN_TYPE="http://schemas.xmlsoap.org/ws/2005/02/sc/dk";
public static final String DEFAULT_DERIVED_KEY_TOKEN_ALGORITHM="http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1";
public static final String DEFAULT_DERIVEDKEYTOKEN_LABEL = "WS-SecureConversationWS-SecureConversation";
URI getAlgorithm();
byte[] getNonce();
long getLength();
long getOffset();
long getGeneration();
String getLabel();
SecretKey generateSymmetricKey(String algorithm) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException;
}
| 30.717391 | 136 | 0.760085 |
5146b8043b00fe840a3cf29d6d7642abb2edce4e | 642 | package com.training.browser;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
public class FireFoxImplementation implements IBrowserImplementation {
@Override
public WebDriver getDriverWithImplementation() {
WebDriverManager.firefoxdriver().setup();
FirefoxOptions ffoptions = new FirefoxOptions();
ffoptions.setCapability("screenResolution", "1280x1024");
ffoptions.setCapability("marionette", true);
return new FirefoxDriver(ffoptions);
}
}
| 29.181818 | 70 | 0.761682 |
6e3cc3aebf9b131bd8950faa1736a27eae42cb5d | 726 | package com.knits.kncare.model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.knits.kncare.model.base.AbstractMemberAuditableEntity;
import lombok.*;
import javax.persistence.*;
@EqualsAndHashCode(callSuper = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "practice_attachment")
public class PracticeAttachment extends AbstractMemberAuditableEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ToString.Exclude
@ManyToOne
@JoinColumn(name="file_id", nullable = false)
private FileDB fileDB;
@ToString.Exclude
@ManyToOne
@JoinColumn(name="practice_id", nullable = false)
private Practice practice;
}
| 23.419355 | 71 | 0.764463 |
6797db14a67979d3767c7fc7157c9833f7456577 | 485 | package Gameplay;
import Assests.MouseModel.MouseModel;
public class Gameplay
{
public static BirdCharacter[] characters = {BirdCharacter.THORD, BirdCharacter.THORD, BirdCharacter.BULK, BirdCharacter.BULK};
public static void main(String[] args)
{
for (BirdCharacter birdCharacter : characters)
{
BirdConsole.addBird(birdCharacter);
}
MouseConsole.addMouse(MouseModel.MOUSELEFICENT, 225);
GameConsole.play();
}
} | 24.25 | 130 | 0.686598 |
490dcd8f05b4c8c2fc5512c81040bbab1b01ca04 | 8,552 | /*
* Copyright 2017 Apereo
*
* 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.tle.web.coursedefaults;
import java.text.ParseException;
import java.util.Date;
import javax.inject.Inject;
import com.tle.annotation.NonNullByDefault;
import com.tle.annotation.Nullable;
import com.tle.common.Check;
import com.tle.common.settings.standard.CourseDefaultsSettings;
import com.tle.common.util.TleDate;
import com.tle.common.util.UtcDate;
import com.tle.core.settings.service.ConfigurationService;
import com.tle.web.sections.SectionInfo;
import com.tle.web.sections.SectionTree;
import com.tle.web.sections.ajax.AjaxGenerator;
import com.tle.web.sections.ajax.handler.AjaxFactory;
import com.tle.web.sections.annotations.Bookmarked;
import com.tle.web.sections.annotations.EventFactory;
import com.tle.web.sections.annotations.EventHandlerMethod;
import com.tle.web.sections.equella.annotation.PlugKey;
import com.tle.web.sections.equella.layout.OneColumnLayout;
import com.tle.web.sections.equella.receipt.ReceiptService;
import com.tle.web.sections.events.RenderEventContext;
import com.tle.web.sections.events.js.EventGenerator;
import com.tle.web.sections.events.js.JSHandler;
import com.tle.web.sections.js.generic.OverrideHandler;
import com.tle.web.sections.render.GenericTemplateResult;
import com.tle.web.sections.render.Label;
import com.tle.web.sections.render.TemplateResult;
import com.tle.web.sections.standard.Button;
import com.tle.web.sections.standard.Calendar;
import com.tle.web.sections.standard.Checkbox;
import com.tle.web.sections.standard.annotations.Component;
import com.tle.web.settings.menu.SettingsUtils;
import com.tle.web.template.Breadcrumbs;
import com.tle.web.template.Decorations;
/**
* @author larry
*/
@SuppressWarnings("nls")
@NonNullByDefault
public class CourseDefaultsSettingsSection
extends
OneColumnLayout<CourseDefaultsSettingsSection.CourseDefaultsSettingsModel>
{
@PlugKey("coursedefaults.title")
private static Label TITLE_LABEL;
@PlugKey("coursedefaults.settings.save.receipt")
private static Label SAVE_RECEIPT_LABEL;
/**
* Constraints on order of dates (ie start <= end) established by notAfter &
* notBefore parameters in the freemarker template.
*/
@Component(name = "sdt", stateful = false)
private Calendar startDate;
@Component(name = "edt", stateful = false)
private Calendar endDate;
@Component
@PlugKey("settings.save.button")
private Button saveButton;
@Component
@PlugKey("settings.clear.button")
private Button clearButton;
@Component(stateful = false)
@PlugKey("portionrestrictions.checkbox")
private Checkbox portionRestrictions;
@EventFactory
private EventGenerator events;
@AjaxFactory
private AjaxGenerator ajax;
private static final String CLEAR_DIV = "clear";
@Inject
private ConfigurationService configService;
@Inject
private ReceiptService receiptService;
@Inject
private CourseDefaultsSettingsPrivilegeTreeProvider securityProvider;
@Override
public void registered(String id, SectionTree tree)
{
super.registered(id, tree);
final JSHandler updateClear = new OverrideHandler(
ajax.getAjaxUpdateDomFunction(tree, this, events.getEventHandler("showClear"), CLEAR_DIV));
startDate.setEventHandler(JSHandler.EVENT_CHANGE, updateClear);
endDate.setEventHandler(JSHandler.EVENT_CHANGE, updateClear);
clearButton.setClickHandler(events.getNamedHandler("clear"));
saveButton.setClickHandler(events.getNamedHandler("save"));
}
/**
*/
@Override
protected TemplateResult setupTemplate(RenderEventContext info)
{
securityProvider.checkAuthorised();
if( !getModel(info).isLoaded() )
{
CourseDefaultsSettings settings = getCourseDefaultsSettings();
portionRestrictions.setChecked(info, settings.isPortionRestrictionsEnabled());
Date start = null;
try
{
if( !Check.isEmpty(settings.getStartDate()) )
{
start = CourseDefaultsSettings.parseDate(settings.getStartDate());
}
}
catch( ParseException pe )
{
// Ignore
}
if( start != null )
{
startDate.setDate(info, new UtcDate(start));
}
Date end = null;
try
{
if( !Check.isEmpty(settings.getEndDate()) )
{
end = CourseDefaultsSettings.parseDate(settings.getEndDate());
}
}
catch( ParseException pe )
{
// Ignore
}
if( end != null )
{
endDate.setDate(info, new UtcDate(end));
}
getModel(info).setLoaded(true);
}
else
{
// filthy, filthy hack to get around the clear button fudging things
// up
portionRestrictions.setChecked(info, portionRestrictions.isChecked(info));
}
checkForDates(info);
return new GenericTemplateResult(viewFactory.createNamedResult(BODY, "coursedefaultssettings.ftl", this));
}
@Override
protected void addBreadcrumbsAndTitle(SectionInfo info, Decorations decorations, Breadcrumbs crumbs)
{
decorations.setTitle(TITLE_LABEL);
crumbs.addToStart(SettingsUtils.getBreadcrumb(info));
checkForDates(info);
}
private CourseDefaultsSettings getCourseDefaultsSettings()
{
return configService.getProperties(new CourseDefaultsSettings());
}
@EventHandlerMethod
public void save(SectionInfo info)
{
saveSystemConstants(info);
receiptService.setReceipt(SAVE_RECEIPT_LABEL);
}
@EventHandlerMethod
public void clear(SectionInfo info)
{
startDate.clearDate(info);
endDate.clearDate(info);
getModel(info).setShowClearLink(false);
getModel(info).setLoaded(true);
}
@EventHandlerMethod
public void showClear(SectionInfo info)
{
checkForDates(info);
}
private void checkForDates(SectionInfo info)
{
CourseDefaultsSettingsModel model = getModel(info);
boolean atLeastOneDateRendered = (startDate.isDateSet(info) || endDate.isDateSet(info));
model.setShowClearLink(atLeastOneDateRendered);
}
private void saveSystemConstants(SectionInfo info)
{
final CourseDefaultsSettings courseDefaultsSettings = getCourseDefaultsSettings();
courseDefaultsSettings.setStartDate(extractFormattedDateFromControl(info, startDate));
courseDefaultsSettings.setEndDate(extractFormattedDateFromControl(info, endDate));
courseDefaultsSettings.setPortionRestrictionsEnabled(portionRestrictions.isChecked(info));
configService.setProperties(courseDefaultsSettings);
getModel(info).setLoaded(false);
}
/**
* static because all variables are passed in , no access to members
* required.
*
* @param info
* @param dateControl
* @return formatted string, or null if no date exists or cannot be
* formatted.
*/
@Nullable
private static String extractFormattedDateFromControl(SectionInfo info, Calendar dateControl)
{
TleDate controlDate = dateControl.getDate(info);
String dateAsString = null;
try
{
dateAsString = CourseDefaultsSettings
.formatDateToPlainString(controlDate == null ? null : controlDate.toDate());
}
catch( IllegalArgumentException iae )
{
// plough on to return null
}
return dateAsString;
}
/**
* @return the startDate
*/
public Calendar getStartDate()
{
return startDate;
}
/**
* @return the endDate
*/
public Calendar getEndDate()
{
return endDate;
}
/**
* @return the saveButton
*/
public Button getSaveButton()
{
return saveButton;
}
/**
* @return the clearButton
*/
public Button getClearButton()
{
return clearButton;
}
public Checkbox getPortionRestrictions()
{
return portionRestrictions;
}
@Override
public Class<CourseDefaultsSettingsModel> getModelClass()
{
return CourseDefaultsSettingsModel.class;
}
public static class CourseDefaultsSettingsModel extends OneColumnLayout.OneColumnLayoutModel
{
@Bookmarked
private boolean loaded;
@Bookmarked(stateful = false)
private boolean showClearLink;
public boolean isLoaded()
{
return loaded;
}
public void setLoaded(boolean loaded)
{
this.loaded = loaded;
}
public boolean isShowClearLink()
{
return showClearLink;
}
public void setShowClearLink(boolean showClearLink)
{
this.showClearLink = showClearLink;
}
}
}
| 26.313846 | 108 | 0.762278 |
7ba10d6fe7009e96e6bc922f4f5d9a391fd1cb0e | 1,499 | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dashbuilder.json;
/**
* Vends out implementation of JsonFactory.
*/
public class Json {
public static JsonString create(String string) {
return instance().create(string);
}
public static JsonBoolean create(boolean bool) {
return instance().create(bool);
}
public static JsonArray createArray() {
return instance().createArray();
}
public static JsonNull createNull() {
return instance().createNull();
}
public static JsonNumber create(double number) {
return instance().create(number);
}
public static JsonObject createObject() {
return instance().createObject();
}
public static JsonFactory instance() {
return new JsonFactory();
}
public static JsonObject parse(String jsonString) {
return instance().parse(jsonString);
}
}
| 27.254545 | 75 | 0.681121 |
ef241e46380750bcb3a4cf4bebac074f52604a21 | 1,703 | package controller;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import org.hibernate.Session;
import util.jsf.FacesUtil;
import util.report.ExecutorRelatorio;
@Named
@RequestScoped
public class RelatorioPedidosEmitidosBean implements Serializable {
private static final long serialVersionUID = 1L;
private Date dataInicio;
private Date dataFim;
@Inject
private FacesContext facesContext;
@Inject
private HttpServletResponse response;
@Inject
private EntityManager manager;
public void emitir() {
Map<String, Object> parametros = new HashMap<>();
parametros.put("data_inicio", this.dataInicio);
parametros.put("data_fim", this.dataFim);
ExecutorRelatorio executor = new ExecutorRelatorio("/relatorios/relatorio_pedidos_emitidos.jasper",
this.response, parametros, "Pedidos_emitidos.pdf");
Session session = this.manager.unwrap(Session.class);
session.doWork(executor);
if (executor.isRelatorioGerado()) {
this.facesContext.responseComplete();
} else {
FacesUtil.addErrorMessage("A execução do relatório não retornou dados.");
}
}
@NotNull
public Date getDataInicio() {
return this.dataInicio;
}
public void setDataInicio(Date dataInicio) {
this.dataInicio = dataInicio;
}
@NotNull
public Date getDataFim() {
return this.dataFim;
}
public void setDataFim(Date dataFim) {
this.dataFim = dataFim;
}
} | 22.706667 | 101 | 0.77569 |
08f6e99c8ee478d754787ac80ddbd4a4f5d7624c | 1,789 | import java.util.*;
public class Prog7{
public static void main(String[] agr){
//int[] a={6, 2, 5, 3};
//int[] b={1, 2};
//int[] c={1};
//shiftLeft(a);
//shiftLeft(b);
//shiftLeft(c);
//System.out.println(Arrays.toString(a));
//System.out.println(Arrays.toString(b));
//System.out.println(Arrays.toString(c));
//int[] c = {6, 2, 5, -4, 3};
//shiftLeftAtI(c, 2);
//System.out.println(Arrays.toString(c));
//int[] a={-3, 0, 7, -19, 0, 2};
//zeroFront(a);
//System.out.println(Arrays.toString(a));
//int[] a={-3, 10, 7, 10, 10, 2};
//withoutTen(a);
//System.out.println(Arrays.toString(a));
}
public static void shiftLeft(int[] a){
int[] ret = new int[a.length];
for(int i = 0; i < a.length-1; i++){
ret[i] = a[i+1];
}
ret[a.length-1]=a[0];
//System.out.println(Arrays.toString(ret));
becauseWeHaveToMODIFYTheSameStuffOMG(a, ret);
}
public static void becauseWeHaveToMODIFYTheSameStuffOMG(int[] x, int[] y){
for(int i = 0; i<x.length; i++){
x[i]=y[i];
}
}
public static void shiftLeftAtI(int[] a, int b){
int[] ret = new int[a.length];
for(int i = 0; i < b; i++){
ret[i] = a[i];
}
for(int i = b; i < a.length-1; i++){
ret[i] = a[i+1];
}
//ret[a.length-1]=a[0];
//System.out.println(Arrays.toString(ret));
becauseWeHaveToMODIFYTheSameStuffOMG(a, ret);
}
public static void withoutTen(int[] a){
for(int i = 0; i<a.length; i++){
if(a[i]==10){
shiftLeftAtI(a, i);
i--;
}
}
}
public static void zeroFront(int[] a){
Arrays.sort(a);
System.out.println(Arrays.binarySearch(a, 0));
int d = Arrays.binarySearch(a, 0);
for(int i=0; i<d; i++)
shiftLeft(a);
}
}
| 27.106061 | 76 | 0.544438 |
db4cf4d4ba22bb133eef8b3f3b6d943f2d43837e | 1,290 | /*
* To change this license header, choose License Headers in Project Properties. To change this
* template file, choose Tools | Templates and open the template in the editor.
*/
package com.hantsylabs.example.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoExceptionTranslator;
import org.springframework.data.mongodb.core.mapping.event.LoggingEventListener;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
/**
*
* @author hantsy
*/
@Configuration
@EnableMongoRepositories(basePackages = "com.hantsylabs.example.spring.repository")
public class MongoConfig extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return "conference-db";
}
@Override
public Mongo mongo() throws Exception {
return new MongoClient("localhost");
}
@Bean
public MongoExceptionTranslator exceptionTranslator() {
return new MongoExceptionTranslator();
}
@Bean
public LoggingEventListener loggingEventListener() {
return new LoggingEventListener();
}
}
| 28.043478 | 94 | 0.804651 |
384f8f5fe2c9175e824b3f1d6c26b7b1cefdf347 | 3,527 | package de.tudarmstadt.informatik.fop.breakout.controllers;
import de.tudarmstadt.informatik.fop.breakout.models.SoundType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.newdawn.slick.openal.Audio;
import org.newdawn.slick.openal.SoundStore;
import java.io.IOException;
import java.util.EnumMap;
/**
* Manages sound loading, playing and caching. It loads the sound files into memory and caches. Then
* the sound type doesn't need to be loaded every time it's accessed.
*/
public class SoundController implements AutoCloseable {
private final Logger logger = LogManager.getLogger();
private final SoundStore soundStore = SoundStore.get();
private final EnumMap<SoundType, Audio> loadedSound = new EnumMap<>(SoundType.class);
public SoundController() {
//load sound drivers
soundStore.init();
}
/**
* @return the sound backend instance
*/
public SoundStore getSoundStore() {
return soundStore;
}
/**
* Loads the sound file from disk and caches it into memory
*
* @param types a list of all sounds that should be loaded
*/
public void load(SoundType... types) {
if (!soundStore.soundWorks()) {
logger.warn("Failed to connect to the sound system");
}
for (SoundType sound : types) {
logger.info("Loading sound file: {}", sound.getSoundPath());
try {
Audio wav = soundStore.getWAV(sound.getSoundPath());
loadedSound.put(sound, wav);
} catch (IOException ioEx) {
logger.error("Failed to load sound file {} - cause {}", sound.name(), ioEx);
}
}
}
/**
* Play a sound effect without looping and with from the user specified volume
*
* @param type the sound type that should be played
*/
public void playEffect(SoundType type) {
Audio audio = loadedSound.get(type);
if (audio == null) {
logger.warn("Sound file {} isn't loaded and cannot be played now", type.name());
return;
}
logger.info("Playing sound effect {}", type.name());
audio.playAsSoundEffect(1f, 1f, false);
}
/**
* Play this sound type on the music channel
*
* @param type the sound type that should be played as a loop
*/
public void playMusic(SoundType type) {
Audio audio = loadedSound.get(type);
if (audio == null) {
logger.warn("Sound file {} isn't loaded and cannot be played now", type.name());
return;
}
logger.info("Playing music {}", type.name());
//turn it on if it was off before
soundStore.setMusicOn(true);
audio.playAsMusic(1f, 1f, true);
}
/**
* Set the pitch at which the current music is being played
*
* @param pitch The pitch at which the current music is being played
*/
public void setMusicPitch(float pitch) {
soundStore.setMusicPitch(pitch);
}
@Override
public void close() {
logger.debug("Cleaning up sound resources");
//stop the music in order to release the native data
soundStore.setMusicOn(false);
soundStore.setSoundsOn(false);
//release allocated memory
for (Audio audio : loadedSound.values()) {
audio.stop();
audio.release();
}
soundStore.disable();
soundStore.clear();
}
}
| 29.889831 | 100 | 0.614687 |
55ae183f7a7cba3e2d707d905e0137c420841e11 | 637 | package com.crazicrafter1.siege.tabcomplete;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.List;
public class TabInvader extends BaseTabCompleter {
public TabInvader() {
super("invader");
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
ArrayList<String> list = new ArrayList<>();
if (args.length == 1) {
list.add("undead_ghoul");
list.add("zombie");
list.add("nemesis");
}
return list;
}
}
| 21.965517 | 107 | 0.638932 |
21bf80f3c2d3edcdb73dac7eb250675c87da1d95 | 2,413 | /*
* Copyright (c) 2018 - Frank Hossfeld
*
* 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 de.gishmo.gwt.example.mvp4g2.mail.client.ui.status;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.themebuilder.base.client.config.ThemeDetails;
import com.sencha.gxt.widget.core.client.container.MarginData;
import com.sencha.gxt.widget.core.client.container.SimpleContainer;
import com.github.mvp4g.mvp4g2.core.ui.LazyReverseView;
public class StatusView
extends LazyReverseView<IStatusView.Presenter>
implements IStatusView {
private static ThemeDetails themeDetails = GWT.create(ThemeDetails.class);
private SimpleContainer container;
private Label label;
public StatusView() {
super();
}
@Override
public Widget asWidget() {
return this.container;
}
@Override
public void setStatus(String status) {
this.label.setText(status);
}
public void createView() {
this.container = new SimpleContainer();
this.container.getElement()
.getStyle()
.setProperty("borderTop",
themeDetails.borderColor() + " 1px solid");
this.label = new Label("loading ...");
this.label.getElement()
.getStyle()
.setProperty("fontSize",
"24px");
this.label.getElement()
.getStyle()
.setProperty("fontFamily",
themeDetails.panel()
.font()
.family());
this.label.getElement()
.getStyle()
.setProperty("color",
themeDetails.borderColor());
this.container.add(this.label,
new MarginData(6));
}
}
| 30.544304 | 81 | 0.630336 |
d5c56818b67695e9d9076b4511b52953b7158fcc | 4,958 | package org.unsurv;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.PersistableBundle;
import android.preference.PreferenceManager;
import android.util.Log;
import androidx.lifecycle.ViewModelProviders;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
// TODO maybe replace asynctask with LocalBroadcastmanager for API_KEY_CHANGED
/**
* This class handles the recurring synchronization jobs that synchronize the local db with the
* server.
*/
public class SyncIntervalSchedulerJobService extends JobService {
private String baseUrl;
private String areaQuery;
private String startQuery;
private boolean downloadImages;
private SynchronizedCameraRepository synchronizedCameraRepository;
CameraRepository cameraRepository;
CameraViewModel cameraViewModel;
private SharedPreferences sharedPreferences;
static String TAG = "SyncIntervalSchedulerJobService";
SimpleDateFormat timestampIso8601SecondsAccuracy;
@Override
public boolean onStartJob(JobParameters jobParameters) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
synchronizedCameraRepository = new SynchronizedCameraRepository(getApplication());
cameraRepository = new CameraRepository(getApplication());
PersistableBundle intervalSchedulerExtras = jobParameters.getExtras();
baseUrl = intervalSchedulerExtras.getString("baseUrl");
areaQuery = intervalSchedulerExtras.getString("area");
startQuery = "start=" + sharedPreferences.getString("lastUpdated", "01-01-2000");
downloadImages = intervalSchedulerExtras.getBoolean("downloadImages");
timestampIso8601SecondsAccuracy = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
// aborts current query if API key expired. starts same query after a new API key is aquired in refreshApiKeyAsyncTask
try {
Date apiKeyExpiration = timestampIso8601SecondsAccuracy.parse(sharedPreferences.getString("apiKeyExpiration", ""));
Date currentDate = new Date(System.currentTimeMillis());
if (apiKeyExpiration.before(currentDate)){
// Abort current query after requesting a new API key.
new SyncIntervalSchedulerJobService.refreshApiKeyAsyncTask().execute();
return false;
}
} catch (ParseException pse) {
Log.i(TAG, "queryServerForCamera: " + pse.toString());
}
SynchronizationUtils.downloadCamerasFromServer(
baseUrl,
areaQuery,
true,
synchronizedCameraRepository,
sharedPreferences,
this);
//List<SurveillanceCamera> camerasToUpload = cameraRepository.getCamerasForUpload();
// SynchronizationUtils.uploadSurveillanceCameras(camerasToUpload, baseUrl, sharedPreferences, null, cameraRepository, true);
SimpleDateFormat timestampIso8601 = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
timestampIso8601.setTimeZone(TimeZone.getTimeZone("UTC"));
sharedPreferences.edit().putString(
"lastUpdated",
timestampIso8601.format(new Date(System.currentTimeMillis())))
.apply();
return false;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
return false;
}
// gets a new API key if it's expired. requeues original server query afterwards.
private class refreshApiKeyAsyncTask extends AsyncTask<Void, Void, Void> {
refreshApiKeyAsyncTask(){}
@Override
protected Void doInBackground(Void... params) {
SynchronizationUtils.getAPIkey(getApplicationContext(), sharedPreferences);
return null;
}
@Override
protected void onPostExecute(Void nothingness) {
// download images after acquiring a new API key
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
SynchronizationUtils.downloadCamerasFromServer(
baseUrl,
areaQuery,
true,
synchronizedCameraRepository,
sharedPreferences,
getBaseContext());
}
}, 10000);
List<SurveillanceCamera> camerasToUpload = cameraRepository.getCamerasForUpload();
SynchronizationUtils.uploadSurveillanceCameras(camerasToUpload, baseUrl, sharedPreferences, null, cameraRepository, true);
SimpleDateFormat timestampIso8601 = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
timestampIso8601.setTimeZone(TimeZone.getTimeZone("UTC"));
sharedPreferences.edit().putString(
"lastUpdated",
timestampIso8601.format(new Date(System.currentTimeMillis())))
.apply();
}
}
}
| 31.579618 | 129 | 0.726503 |
e0daffc5ae230dc29edead6895d436cf93ff01b4 | 2,515 | package ch.heigvd.quaris.api;
import ch.heigvd.quaris.api.definitions.RegistrationsApi;
import ch.heigvd.quaris.api.dto.RegistrationDTO;
import ch.heigvd.quaris.api.dto.RegistrationSummaryDTO;
import ch.heigvd.quaris.repositories.ApplicationRepository;
import ch.heigvd.quaris.models.Application;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Olivier Liechti
*/
@RestController
public class RegistrationsEndpoint implements RegistrationsApi {
@Autowired
private ApplicationRepository applicationsRepository;
@Override
public ResponseEntity<List<RegistrationSummaryDTO>> registrationsGet() {
List<RegistrationSummaryDTO> result = new ArrayList<>();
for (Application application : applicationsRepository.findAll()) {
RegistrationSummaryDTO rs = new RegistrationSummaryDTO();
rs.setApplicationName(application.getName());
result.add(rs);
}
return ResponseEntity.ok(result);
}
@Override
public ResponseEntity<Void> registrationsPost(@RequestBody RegistrationDTO registration) {
System.out.println(registration);
if(registration.getPassword() != null && registration.getApplicationName() != null && registration.getPassword().length() >= 5) {
Application newApplication = new Application();
newApplication.setName(registration.getApplicationName());
String passwordHash = registration.getPassword(); // TODO hash password
newApplication.setPasswordHash(passwordHash);
System.out.println("> New registration:");
System.out.println(registration); // DEV
try {
applicationsRepository.save(newApplication);
return ResponseEntity.status(HttpStatus.CREATED).build();
} catch (DataIntegrityViolationException e) {
System.out.println(e.getMessage());
System.out.println(e.getClass());
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
}
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
}
| 39.296875 | 137 | 0.715308 |
141778c576179f34872b807a4ae82da52a1b6c2a | 4,180 | package com.ivan.tl.service.todo.dynamodb;
import com.ivan.tl.meta.DynamoDBProfile;
import com.ivan.tl.model.TodoItem;
import com.ivan.tl.model.TodoItemId;
import com.ivan.tl.model.TodoItemStatus;
import com.ivan.tl.service.todo.TodoListService;
import com.ivan.tl.service.todo.dynamodb.entity.TodoItemEntity;
import com.ivan.tl.service.todo.dynamodb.repository.EntityIdGeneratorRepository;
import com.ivan.tl.service.todo.dynamodb.repository.TodoItemRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@Service
@DynamoDBProfile
public class DynamoDBTodoListService implements TodoListService {
private static final Logger logger = LoggerFactory.getLogger(DynamoDBTodoListService.class);
private final TodoItemRepository todoItemRepository;
private final EntityIdGeneratorRepository entityIdGeneratorRepository;
public DynamoDBTodoListService(TodoItemRepository todoItemRepository, EntityIdGeneratorRepository entityIdGeneratorRepository) {
this.todoItemRepository = todoItemRepository;
this.entityIdGeneratorRepository = entityIdGeneratorRepository;
}
@Override
public List<TodoItem> getAllItems() {
return StreamSupport.stream(this.todoItemRepository.findAll().spliterator(), false)
.map(entity -> new TodoItem(entity.getId(), entity.getName(), entity.getDescription(), entity.isDone()))
.collect(Collectors.toList());
}
@Override
public TodoItemId createItem(final TodoItem todoItem) {
Assert.notNull(todoItem, "Todo item must not be null");
final Long newId = this.entityIdGeneratorRepository.incrementCounter(TodoItemEntity.TABLE_NAME);
final TodoItemEntity todoItemEntity = new TodoItemEntity();
todoItemEntity.setId(newId);
todoItemEntity.setName(todoItem.getName());
todoItemEntity.setDescription(todoItem.getDescription());
this.todoItemRepository.save(todoItemEntity);
logger.info("Created todo item - {}", todoItemEntity);
return new TodoItemId(newId);
}
@Override
public void updateItem(final TodoItem todoItem) {
Assert.notNull(todoItem, "Todo item must not be null");
Assert.notNull(todoItem.getId(), "Todo item id must not be null");
final TodoItemEntity savedItem = this.todoItemRepository.findById(todoItem.getId())
.orElseThrow(IllegalStateException::new);
savedItem.setName(todoItem.getName());
savedItem.setDescription(todoItem.getDescription());
savedItem.setDone(todoItem.isDone());
this.todoItemRepository.save(savedItem);
logger.info("Todo item has been updated - {}", savedItem);
}
@Override
public TodoItem getItem(final TodoItemId itemId) {
Assert.isTrue(TodoItemId.isNotEmpty(itemId), "Todo item id must not be null");
final TodoItemEntity todoItemEntity = this.todoItemRepository.findById(itemId.getId())
.orElseThrow(IllegalStateException::new);
return new TodoItem(todoItemEntity.getId(), todoItemEntity.getName(), todoItemEntity.getDescription(), todoItemEntity.isDone());
}
@Override
public void removeItem(final TodoItemId itemId) {
Assert.isTrue(TodoItemId.isNotEmpty(itemId), "Todo item id must not be null");
todoItemRepository.deleteById(itemId.getId());
logger.info("Todo item has been deleted - {}", itemId);
}
@Override
public void updateStatus(final TodoItemId itemId, TodoItemStatus status) {
Assert.isTrue(TodoItemId.isNotEmpty(itemId), "Todo item id must not be null");
final TodoItemEntity todoItemEntity = todoItemRepository.findById(itemId.getId())
.orElseThrow(IllegalArgumentException::new);
todoItemEntity.setDone(status.isDone());
this.todoItemRepository.save(todoItemEntity);
logger.info("Todo item({}) status has been changed to {}", itemId, todoItemEntity.isDone());
}
}
| 40.192308 | 136 | 0.730622 |
29893668023fd9ab2c8adfe9e88eed1c9e35d394 | 1,577 | package com.google.android.play.core.splitcompat;
import android.content.Context;
import android.util.Base64;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;
/* renamed from: com.google.android.play.core.splitcompat.p */
public final class C2032p {
/* renamed from: a */
private static ThreadPoolExecutor f895a;
/* renamed from: a */
public static Context m933a(Context context) {
Context applicationContext = context.getApplicationContext();
return applicationContext != null ? applicationContext : context;
}
/* renamed from: a */
public static String m934a(byte[] bArr) {
try {
MessageDigest instance = MessageDigest.getInstance(MessageDigestAlgorithms.SHA_256);
instance.update(bArr);
return Base64.encodeToString(instance.digest(), 11);
} catch (NoSuchAlgorithmException unused) {
return "";
}
}
/* renamed from: a */
public static Executor m935a() {
if (f895a == null) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, new LinkedBlockingQueue(), new C2018b());
f895a = threadPoolExecutor;
threadPoolExecutor.allowCoreThreadTimeOut(true);
}
return f895a;
}
}
| 34.282609 | 144 | 0.696259 |
8496fbece21176fe17869f530cc9af11c084e05e | 1,987 | import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.extensions.PluginId;
public class PluginProperties {
private static final PluginProperties instance = new PluginProperties();
private final PropertiesComponent applicationProperties;
private final String pluginId;
private Properties cachedUserProperties;
private PluginProperties() {
applicationProperties = PropertiesComponent.getInstance();
PluginId id = PluginManagerCore.getPluginByClassName(this.getClass().getName());
pluginId = (id != null) ? id.getIdString() : "";
}
public static PluginProperties getInstance() {
return instance;
}
public void setValues(Properties properties) {
applicationProperties.setValue(String.join(".", pluginId, "userName"), properties.getUserName());
applicationProperties.setValue(String.join(".", pluginId, "apiToken"), properties.getApiToken());
applicationProperties.setValue(String.join(".", pluginId, "jenkinsUrl"), properties.getJenkinsUrl());
applicationProperties.setValue(String.join(".", pluginId, "sslVerifyDisabled"), properties.isSslVerifyDisabled());
cachedUserProperties = properties;
}
public Properties getValues() {
if (cachedUserProperties == null) {
cachedUserProperties = new Properties();
cachedUserProperties.setUserName(applicationProperties.getValue(String.join(".", pluginId, "userName"), ""));
cachedUserProperties.setApiToken(applicationProperties.getValue(String.join(".", pluginId, "apiToken"), ""));
cachedUserProperties.setJenkinsUrl(applicationProperties.getValue(String.join(".", pluginId, "jenkinsUrl"), ""));
cachedUserProperties.setSslVerifyDisabled(applicationProperties.getBoolean(String.join(".", pluginId, "sslVerifyDisabled"), false));
}
return cachedUserProperties;
}
} | 49.675 | 144 | 0.719175 |
e134a70ce64b8090ef62829e32ddf99f2d064a1a | 11,036 | package tv.dyndns.kishibe.qmaclone.client.ui;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.DomEvent;
import com.google.gwt.event.dom.client.HasAllMouseHandlers;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.dom.client.HasMouseWheelHandlers;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.dom.client.MouseWheelEvent;
import com.google.gwt.event.dom.client.MouseWheelHandler;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.widgetideas.graphics.client.CanvasGradient;
import com.google.gwt.widgetideas.graphics.client.Color;
import com.google.gwt.widgetideas.graphics.client.GWTCanvas;
/**
* {@link PopupPanel} を用いて全面に表示される {@link GWTCanvas} 。 {@link Widget} の左上の座標を基準座標として表示する。
*
* @author nodchip
*/
public class PopupCanvas implements HasClickHandlers, HasAllMouseHandlers, HasMouseWheelHandlers {
private final Map<EventHandler, DomEvent.Type<EventHandler>> eventHandlers = new HashMap<EventHandler, DomEvent.Type<EventHandler>>();
private final Widget offset;
private int width;
private int height;
private final PopupPanel popupPanel;
private GWTCanvas canvas;
private HandlerRegistration resizeHandlerRegistration;
private HandlerRegistration scrollHandlerRegistration;
public PopupCanvas(Widget offset, int width, int height) {
this.offset = offset;
this.width = width;
this.height = height;
popupPanel = new PopupPanel(false, false);
popupPanel.setStyleName("popup-canvas-background");
prepare();
}
public void prepare() {
canvas = new GWTCanvas(width, height);
popupPanel.setWidget(canvas);
for (Entry<EventHandler, DomEvent.Type<EventHandler>> entry : eventHandlers.entrySet()) {
canvas.addDomHandler(entry.getKey(), entry.getValue());
}
}
// 以下PopupPanelより
/**
* 画面上に表示する。 描画メソッドはこのメソッドを呼んだ後でないと効果がない。
*/
public void show() {
updatePopupPosition();
popupPanel.show();
resizeHandlerRegistration = Window.addResizeHandler(new ResizeHandler() {
@Override
public void onResize(ResizeEvent event) {
updatePopupPosition();
}
});
scrollHandlerRegistration = Window.addWindowScrollHandler(new Window.ScrollHandler() {
public void onWindowScroll(com.google.gwt.user.client.Window.ScrollEvent event) {
updatePopupPosition();
}
});
}
private void updatePopupPosition() {
popupPanel.setPopupPosition(offset.getAbsoluteLeft(), offset.getAbsoluteTop());
}
public void hide() {
if (scrollHandlerRegistration != null) {
scrollHandlerRegistration.removeHandler();
scrollHandlerRegistration = null;
}
if (resizeHandlerRegistration != null) {
resizeHandlerRegistration.removeHandler();
resizeHandlerRegistration = null;
}
popupPanel.hide();
}
public int getPopupLeft() {
return popupPanel.getPopupLeft();
}
public int getPopupTop() {
return popupPanel.getPopupTop();
}
public void setPopupPosition(int left, int top) {
popupPanel.setPopupPosition(left, top);
}
// 以下GWTCanvasより
public void arc(double x, double y, double radius, double startAngle, double endAngle,
boolean antiClockwise) {
canvas.arc(x, y, radius, startAngle, endAngle, antiClockwise);
}
public void beginPath() {
canvas.beginPath();
}
public void clear() {
canvas.clear();
}
public void closePath() {
canvas.closePath();
}
public CanvasGradient createLinearGradient(double x0, double y0, double x1, double y1) {
return canvas.createLinearGradient(x0, y0, x1, y1);
}
public CanvasGradient createRadialGradient(double x0, double y0, double r0, double x1,
double y1, double r1) {
return canvas.createRadialGradient(x0, y0, r0, x1, y1, r1);
}
public void cubicCurveTo(double cp1x, double cp1y, double cp2x, double cp2y, double x, double y) {
canvas.cubicCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
}
public void drawImage(ImageElement img, double offsetX, double offsetY) {
canvas.drawImage(img, offsetX, offsetY);
}
public void drawImage(ImageElement img, double offsetX, double offsetY, double width,
double height) {
canvas.drawImage(img, offsetX, offsetY, width, height);
}
public void drawImage(ImageElement img, double sourceX, double sourceY, double sourceWidth,
double sourceHeight, double destX, double destY, double destWidth, double destHeight) {
canvas.drawImage(img, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth,
destHeight);
}
public void fill() {
canvas.fill();
}
public void fillRect(double startX, double startY, double width, double height) {
canvas.fillRect(startX, startY, width, height);
}
public int getCoordHeight() {
return canvas.getCoordHeight();
}
public int getCoordWidth() {
return canvas.getCoordWidth();
}
public double getGlobalAlpha() {
return canvas.getGlobalAlpha();
}
public String getGlobalCompositeOperation() {
return canvas.getGlobalCompositeOperation();
}
public String getLineCap() {
return canvas.getLineCap();
}
public String getLineJoin() {
return canvas.getLineJoin();
}
public double getLineWidth() {
return canvas.getLineWidth();
}
public double getMiterLimit() {
return canvas.getMiterLimit();
}
public void lineTo(double x, double y) {
canvas.lineTo(x, y);
}
public void moveTo(double x, double y) {
canvas.moveTo(x, y);
}
public void quadraticCurveTo(double cpx, double cpy, double x, double y) {
canvas.quadraticCurveTo(cpx, cpy, x, y);
}
public void rect(double startX, double startY, double width, double height) {
canvas.rect(startX, startY, width, height);
}
public void resize(int width, int height) {
this.width = width;
this.height = height;
canvas.resize(width, height);
}
public void restoreContext() {
canvas.restoreContext();
}
public void rotate(double angle) {
canvas.rotate(angle);
}
public void saveContext() {
canvas.saveContext();
}
public void scale(double x, double y) {
canvas.scale(x, y);
}
public void setBackgroundColor(Color color) {
canvas.setBackgroundColor(color);
}
public void setCoordHeight(int height) {
canvas.setCoordHeight(height);
}
public void setCoordSize(int width, int height) {
canvas.setCoordSize(width, height);
}
public void setCoordWidth(int width) {
canvas.setCoordWidth(width);
}
public void setFillStyle(CanvasGradient grad) {
canvas.setFillStyle(grad);
}
public void setFillStyle(Color color) {
canvas.setFillStyle(color);
}
public void setGlobalAlpha(double alpha) {
canvas.setGlobalAlpha(alpha);
}
public void setGlobalCompositeOperation(String globalCompositeOperation) {
canvas.setGlobalCompositeOperation(globalCompositeOperation);
}
public void setLineCap(String lineCap) {
canvas.setLineCap(lineCap);
}
public void setLineJoin(String lineJoin) {
canvas.setLineJoin(lineJoin);
}
public void setLineWidth(double width) {
canvas.setLineWidth(width);
}
public void setMiterLimit(double miterLimit) {
canvas.setMiterLimit(miterLimit);
}
public void setPixelHeight(int height) {
canvas.setPixelHeight(height);
}
public void setPixelWidth(int width) {
canvas.setPixelWidth(width);
}
public void setStrokeStyle(CanvasGradient grad) {
canvas.setStrokeStyle(grad);
}
public void setStrokeStyle(Color color) {
canvas.setStrokeStyle(color);
}
public void stroke() {
canvas.stroke();
}
public void strokeRect(double startX, double startY, double width, double height) {
canvas.strokeRect(startX, startY, width, height);
}
public void transform(double m11, double m12, double m21, double m22, double dx, double dy) {
canvas.transform(m11, m12, m21, m22, dx, dy);
}
public void translate(double x, double y) {
canvas.translate(x, y);
}
@Override
public void fireEvent(GwtEvent<?> event) {
canvas.fireEvent(event);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public HandlerRegistration addMouseDownHandler(MouseDownHandler handler) {
eventHandlers.put(handler, (DomEvent.Type) MouseDownEvent.getType());
if (canvas != null) {
canvas.addDomHandler(handler, MouseDownEvent.getType());
}
return null;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public HandlerRegistration addMouseUpHandler(MouseUpHandler handler) {
eventHandlers.put(handler, (DomEvent.Type) MouseUpEvent.getType());
if (canvas != null) {
canvas.addDomHandler(handler, MouseUpEvent.getType());
}
return null;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public HandlerRegistration addMouseOutHandler(MouseOutHandler handler) {
eventHandlers.put(handler, (DomEvent.Type) MouseOutEvent.getType());
if (canvas != null) {
canvas.addDomHandler(handler, MouseOutEvent.getType());
}
return null;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public HandlerRegistration addMouseOverHandler(MouseOverHandler handler) {
eventHandlers.put(handler, (DomEvent.Type) MouseOverEvent.getType());
if (canvas != null) {
canvas.addDomHandler(handler, MouseOverEvent.getType());
}
return null;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public HandlerRegistration addMouseMoveHandler(MouseMoveHandler handler) {
eventHandlers.put(handler, (DomEvent.Type) MouseMoveEvent.getType());
if (canvas != null) {
canvas.addDomHandler(handler, MouseMoveEvent.getType());
}
return null;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public HandlerRegistration addMouseWheelHandler(MouseWheelHandler handler) {
eventHandlers.put(handler, (DomEvent.Type) MouseWheelEvent.getType());
if (canvas != null) {
canvas.addDomHandler(handler, MouseWheelEvent.getType());
}
return null;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public HandlerRegistration addClickHandler(ClickHandler handler) {
eventHandlers.put(handler, (DomEvent.Type) ClickEvent.getType());
if (canvas != null) {
canvas.addDomHandler(handler, ClickEvent.getType());
}
return null;
}
}
| 27.59 | 135 | 0.750181 |
a4d6b7661691afb34e1a70e7fb5f6fa605c1fde6 | 527 | package com.blastedstudios.gdxworld.util;
import java.io.FileFilter;
import java.io.InputStream;
import java.io.OutputStream;
import net.xeoh.plugins.base.Plugin;
import com.badlogic.gdx.files.FileHandle;
public interface ISerializer extends Plugin{
Object load(InputStream stream) throws Exception;
Object load(FileHandle selectedFile) throws Exception;
void save(FileHandle selectedFile, Object object) throws Exception;
void save(OutputStream stream, Object object) throws Exception;
FileFilter getFileFilter();
}
| 29.277778 | 69 | 0.817837 |
bd13afce8dcb74cbdefc5d876ab1bc5a35925698 | 574 | package net.minecraft.src;
class TMIStateButtonData {
public static final String COPYRIGHT = "All of TooManyItems except for thesmall portion excerpted from the original Minecraft game is copyright 2011Marglyph. TooManyItems is free for personal use only. Do not redistributeTooManyItems, including in mod packs, and do not use TooManyItems' sourcecode or graphics in your own mods.";
public int state;
public int action;
public static final int STATE = 0;
public static final int CLEAR = 1;
public TMIStateButtonData(int i, int j) {
state = i;
action = j;
}
}
| 38.266667 | 331 | 0.773519 |
9c666417d68ee6f9af7963bddfc593cca87cf92c | 735 | package org.applesline.aim.common.codec;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.applesline.aim.common.req.AimRequest;
import java.util.List;
/**
* @author liuyaping
* 创建时间:2020年04月29日
*/
@Sharable
public class AimRequestDecoder extends MessageToMessageDecoder<String> {
private static final Gson GSON = new GsonBuilder().create();
@Override
protected void decode(ChannelHandlerContext ctx, String msg, List<Object> out) throws Exception {
out.add(GSON.fromJson(msg, AimRequest.class));
}
}
| 28.269231 | 102 | 0.746939 |
39f22cca83888f0b9d0fd6fff6013420911c2864 | 43 | package ast;
public interface ASTNode {
}
| 8.6 | 26 | 0.744186 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.