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 |
|---|---|---|---|---|---|
07fd1504148010244d93333e3ea87993a3e33a2f | 901 | package com.hzqing.common.core.rest.result;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.io.Serializable;
/**
* 结果响应
* @author hzq
*/
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RestResult<T> implements Serializable {
private static final long serialVersionUID = -450599376115985279L;
/**
* 请求响应码
*/
private String code;
/**
* 响应吗对应的提示信息
*/
private String msg;
/**
* 返回的数据
*/
private RestResultData<T> data;
public RestResult(String code, String msg, T attributes) {
this.code = code;
this.msg = msg;
this.data = createBaseResultData(attributes);
}
public RestResultData<T> createBaseResultData(T attributes){
RestResultData<T> data = new RestResultData<>();
data.setAttributes(attributes);
return data;
}
}
| 19.586957 | 70 | 0.651498 |
ae53bb21037e137871d79c3c34a3206c38226e05 | 226 | package com.fairy.beans.ioc.pojo;
import lombok.Data;
import org.springframework.stereotype.Component;
/**
* @author :鹿@少年
* @date :Created in 2021/11/30 21:29
* @description:
*/
@Data
@Component
public class User {
}
| 13.294118 | 48 | 0.70354 |
a54e0a04f9e76d586b46e33d61187f01c14fd24b | 441 | package com.zblumenf.spring.data.gremlin.conversion.source.writer;
import com.zblumenf.spring.data.gremlin.conversion.source.GremlinSource;
import org.springframework.lang.NonNull;
import java.lang.reflect.Field;
public abstract class AbstractPropertyWriter {
protected static void setPropertyFromField(@NonNull GremlinSource source, @NonNull Field field, Object value) {
source.setProperty(field.getName(), value);
}
}
| 29.4 | 115 | 0.791383 |
4943fd799ff19983b21844a343d9f05be065b3e3 | 8,903 | /*===========================================================================
Copyright (C) 2008-2011 by the Okapi Framework contributors
-----------------------------------------------------------------------------
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/
package net.sf.okapi.steps.xliffkit.opc;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import net.sf.okapi.common.Event;
import net.sf.okapi.common.EventType;
import net.sf.okapi.common.IParameters;
import net.sf.okapi.common.LocaleId;
import net.sf.okapi.common.Util;
import net.sf.okapi.common.exceptions.OkapiIOException;
import net.sf.okapi.common.filters.AbstractFilter;
import net.sf.okapi.common.filterwriter.IFilterWriter;
import net.sf.okapi.common.resource.ITextUnit;
import net.sf.okapi.common.resource.Property;
import net.sf.okapi.common.resource.RawDocument;
import net.sf.okapi.common.resource.StartDocument;
import net.sf.okapi.common.resource.StartSubDocument;
import net.sf.okapi.filters.xliff.XLIFFFilter;
import net.sf.okapi.lib.beans.sessions.OkapiJsonSession;
import net.sf.okapi.steps.xliffkit.reader.TextUnitMerger;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
public class OPCPackageReader extends AbstractFilter {
private OPCPackage pack;
private OkapiJsonSession session = new OkapiJsonSession();
private Event event;
private LinkedList<PackagePart> coreParts = new LinkedList<PackagePart>();
private PackagePart activePart;
private PackagePart resourcesPart;
private XLIFFFilter xliffReader;
private TextUnitMerger merger;
private LocaleId srcLoc;
private String outputEncoding;
private IFilterWriter filterWriter;
private boolean generateTargets = false;
private String outputPath;
private boolean cacheEvents = false;
private LinkedList<Event> events = new LinkedList<Event>();
//private Event sde;
// private LocaleId trgLoc;
public OPCPackageReader(TextUnitMerger merger) {
super();
this.merger = merger;
}
@Override
protected boolean isUtf8Bom() {
return false;
}
@Override
protected boolean isUtf8Encoding() {
return false;
}
private void writeEvent(Event event) {
if (!generateTargets) return;
if (filterWriter == null) return;
if (events == null) return;
if (cacheEvents) {
events.add(event);
}
else {
while (events.size() > 0)
filterWriter.handleEvent(events.poll());
filterWriter.handleEvent(event);
}
}
@Override
public void close() {
clearParts();
session.end();
try {
pack.close();
} catch (IOException e) {
throw new OkapiIOException("OPCPackageReader: cannot close package");
}
}
private void clearParts() {
coreParts.clear();
activePart = null;
resourcesPart = null;
}
@Override
public IParameters getParameters() {
return null;
}
@Override
public boolean hasNext() {
return event != null;
}
@Override
public Event next() {
Event prev = event;
event = deserializeEvent();
return prev;
}
/*
* Deserializes events from JSON files in OPC package
* @return null if no events are available
*/
private Event deserializeEvent() {
Event event = null;
if (activePart == null) {
activePart = coreParts.poll();
if (activePart == null)
return null;
else
resourcesPart = OPCPackageUtil.getResourcesPart(activePart);
try {
if (resourcesPart != null)
session.start(resourcesPart.getInputStream());
} catch (IOException e) {
throw new OkapiIOException("OPCPackageReader: cannot get resources from package", e);
}
// Create XLIFF filter for the core document
if (xliffReader != null) {
xliffReader.close();
xliffReader = null;
}
xliffReader = new XLIFFFilter();
try {
// Here targetLocale is set to srcLoc, actual target locale is taken from the StartSubDocument's property targetLocale
xliffReader.open(new RawDocument(activePart.getInputStream(), "UTF-8", srcLoc, srcLoc));
} catch (IOException e) {
throw new RuntimeException(String.format("OPCPackageReader: cannot open input stream for %s",
activePart.getPartName().getName()), e);
}
}
event = session.deserialize(Event.class);
if (event == null) {
session.end();
activePart = null;
return deserializeEvent(); // Recursion until all parts are tried
} else
switch (event.getEventType()) {
case START_DOCUMENT:
processStartDocument(event);
break;
case END_DOCUMENT:
processEndDocument(event);
break;
case TEXT_UNIT:
processTextUnit(event); // updates tu with a target from xliff
break;
case START_SUBDOCUMENT:
case START_GROUP:
case END_SUBDOCUMENT:
case END_GROUP:
case DOCUMENT_PART:
writeEvent(event);
}
return event;
}
@Override
public void open(RawDocument input) {
open(input, false);
}
@Override
public void open(RawDocument input, boolean generateSkeleton) {
try {
srcLoc = input.getSourceLocale();
//trgLoc = input.getTargetLocale();
pack = OPCPackage.open(input.getStream());
} catch (Exception e) {
throw new OkapiIOException("OPCPackageReader: cannot open package", e);
}
clearParts();
coreParts.addAll(OPCPackageUtil.getCoreParts(pack));
event = deserializeEvent();
}
@Override
public void setParameters(IParameters params) {
}
private ITextUnit getNextXliffTu() {
if (xliffReader == null)
throw new RuntimeException("OPCPackageReader: xliffReader is not initialized");
Event ev = null;
while (xliffReader.hasNext()) {
ev = xliffReader.next();
if (ev == null) return null;
if (ev.getEventType() == EventType.START_SUBDOCUMENT) {
StartSubDocument startSubDoc = (StartSubDocument)ev.getResource();
Property prop = startSubDoc.getProperty("targetLanguage");
if ( prop != null ) {
LocaleId trgLoc = LocaleId.fromString(prop.getValue());
merger.setTrgLoc(trgLoc);
filterWriter.setOptions(trgLoc, outputEncoding);
cacheEvents = false;
}
}
if (ev.getEventType() == EventType.TEXT_UNIT) {
return ev.getTextUnit();
}
}
return null;
}
private void processStartDocument (Event event) {
// Translate src doc name for writers
StartDocument startDoc = (StartDocument)event.getResource();
String srcName = startDoc.getName();
String partName = activePart.getPartName().toString();
String outFileName = outputPath + Util.getDirectoryName(partName) + "/" + Util.getFilename(srcName, true);
filterWriter = startDoc.getFilterWriter();
//System.out.println(startDoc.getName());
if (generateTargets) {
File outputFile = new File(outFileName);
Util.createDirectories(outputFile.getAbsolutePath());
filterWriter.setOutput(outputFile.getAbsolutePath());
//sde = event; // Store for delayed processing
cacheEvents = true; // In case output locale is not known until START_SUBDOCUMENT
writeEvent(event);
}
}
private void processEndDocument (Event event) {
writeEvent(event);
if (generateTargets)
filterWriter.close();
}
private void processTextUnit(Event event) {
if (merger == null) return;
ITextUnit tu = event.getTextUnit();
ITextUnit xtu = getNextXliffTu();
if (xtu == null) return;
// // Set tu source from xtu source
// TextContainer tc = tu.getSource(); // tu source is empty string + codes in JSON
// TextFragment xtf = xtu.getSource().getUnSegmentedContentCopy();
// tc.append(xtf.getCodedText());
// //tu.setSource(xtu.getSource());
merger.mergeTargets(tu, xtu);
writeEvent(event);
}
public void setGeneratorOptions(String outputEncoding, String outputPath) {
this.outputEncoding = outputEncoding;
this.generateTargets = !Util.isEmpty(outputPath);
this.outputPath = outputPath;
}
}
| 30.7 | 124 | 0.679659 |
c57f5b0efd095b216fc88a0a9d186496c9431433 | 891 | package presentation;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.ClientService;
import service.ClientServiceImpl;
public class ModifierClientServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
ClientService service = new ClientServiceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final int id = Integer.parseInt(request.getParameter("idClient"));
response.sendRedirect(this.getServletContext().getContextPath() + "/editclient?idClient="+id);
}
}
| 30.724138 | 96 | 0.814815 |
e592c3bdda4812ea1b4b856c218c0cd1456807ee | 878 | package com.leetcode.algorithm.medium.topkfrequentwords;
import java.util.*;
class Solution {
public List<String> topKFrequent(String[] words, int k) {
HashMap<String, Integer> map = new HashMap<>();
for (String word: words) {
map.put(word, map.getOrDefault(word, 0) + 1);
}
PriorityQueue<String> queue = new PriorityQueue<>((s1, s2) -> {
int c1 = map.getOrDefault(s1, 0);
int c2 = map.getOrDefault(s2, 0);
if (c1 == c2) {
return s2.compareTo(s1);
} else {
return Integer.compare(c1, c2);
}
});
for (String key: map.keySet()) {
queue.offer(key);
if (queue.size() > k) {
queue.poll();
}
}
ArrayList<String> result = new ArrayList<>();
while (!queue.isEmpty()) {
result.add(queue.poll());
}
Collections.reverse(result);
return result;
}
}
| 23.72973 | 67 | 0.574032 |
a23f19e2d0a9bda980b56b4bd5967560718006cf | 306 | package com.iwa.iwatesting.network.task;
import java.lang.reflect.Constructor;
import java.util.concurrent.Future;
public class CancelTask<T> {
private Future<?> future;
CancelTask(Future<T> future) {
this.future = future;
}
void cancel () {
future.cancel(true);
}
}
| 19.125 | 40 | 0.660131 |
d706e415c804427754cf6c3052780d25b21914d3 | 339 | package com.tazine.design.decorator;
/**
* 装饰器
*
* @author frank
* @since 1.0.0
*/
public class Decorator extends Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
| 15.409091 | 43 | 0.637168 |
e329b8eea7f4f8f7a7ba87138b0b1bd42745bb5a | 7,985 | /*
* Copyright 2013 University of Chicago and Argonne National Laboratory
*
* 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 exm.stc.ic.opt;
import java.io.PrintStream;
import org.apache.log4j.Logger;
import exm.stc.common.Settings;
import exm.stc.common.exceptions.InvalidWriteException;
import exm.stc.common.exceptions.UserException;
import exm.stc.ic.opt.valuenumber.ValueNumber;
import exm.stc.ic.refcount.RefcountPass;
import exm.stc.ic.tree.ICTree.Program;
public class ICOptimizer {
/**
* If true, validate as frequently as possible
*/
public static final boolean SUPER_DEBUG = true;
/**
* Optimize the program and return a new one
*
* NOTE: the input might be modified in-place
* @param icOutput where to log IC between optimiation steps. Null for
* no output
* @return
* @throws InvalidWriteException
*/
public static Program optimize(Logger logger, PrintStream icOutput,
Program prog) throws UserException {
boolean logIC = icOutput != null;
if (logIC) {
prog.log(icOutput, "Initial IC before optimization");
}
long nIterations = Settings.getLongUnchecked(Settings.OPT_MAX_ITERATIONS);
boolean debug = Settings.getBooleanUnchecked(Settings.COMPILER_DEBUG);
preprocess(icOutput, logger, debug, prog);
iterate(icOutput, logger, prog, debug, nIterations);
postprocess(icOutput, logger, debug, prog, nIterations);
if (logIC) {
prog.log(icOutput, "Final optimized IC");
}
return prog;
}
/**
* Do preprocessing optimizer steps
* @param icOutput
* @param logger
* @param debug
* @param program
* @throws Exception
*/
private static void preprocess(PrintStream icOutput, Logger logger,
boolean debug, Program program) throws UserException {
OptimizerPipeline preprocess = new OptimizerPipeline(icOutput);
// Cut down size of IR right away
preprocess.addPass(new PruneFunctions());
// need variable names to be unique for rest of stages
preprocess.addPass(new UniqueVarNames());
// Must fix up variables as frontend doesn't do it
preprocess.addPass(new FlattenNested());
if (debug)
preprocess.addPass(Validate.standardValidator());
preprocess.runPipeline(logger, program, 0);
}
/**
* Do one iteration of the iterative optimizer passes
* @param icOutput
* @param logger
* @param prog
* @param debug
* @param iteration
* @param nIterations
* @throws Exception
*/
private static void iterate(PrintStream icOutput, Logger logger,
Program prog, boolean debug, long nIterations) throws UserException {
// FunctionInline is stateful
FunctionInline inliner = new FunctionInline();
boolean canReorder = true;
for (long iteration = 0; iteration < nIterations; iteration++) {
OptimizerPipeline pipe = new OptimizerPipeline(icOutput);
if (SUPER_DEBUG) {
pipe.setValidator(Validate.standardValidator());
}
// First prune and inline any functions
if (iteration == nIterations / 2) {
// Only makes sense to do periodically
pipe.addPass(new PruneFunctions());
}
if (iteration == 0 || iteration == 3 || iteration == nIterations - 2) {
pipe.addPass(inliner);
}
if ((iteration % 3) == 2) {
// Try to merge instructions into array build
pipe.addPass(new ArrayBuild());
pipe.addPass(new StructBuild());
// Try occasionally to unroll loops. Don't do it on first iteration
// so the code can be shrunk a little first
pipe.addPass(new LoopUnroller());
pipe.addPass(Validate.standardValidator());
}
boolean lastHalf = iteration > nIterations * 2;
// Try to hoist variables out of loops, etc
// Do before forward dataflow since it may open up new opportunites
// switch to aggressive hoisting later on when we have probably done all
// the other optimizations possible
if (canReorder) {
pipe.addPass(new HoistLoops(lastHalf));
}
// Try to reorder instructions for benefit of forward dataflow
// Don't do every iteration, instructions are first
// in original order, then in a different but valid order
if (canReorder && (iteration % 2 == 1)) {
pipe.addPass(new ReorderInstructions());
}
if (iteration % 3 == 0) {
pipe.addPass(new PropagateAliases());
}
if (iteration == nIterations - 2) {
// Towards end, inline explicit waits and disallow reordering
canReorder = false;
}
// ValueNumber is a key pass that reduces a lot of redundancy
pipe.addPass(new ValueNumber(canReorder));
// This loop optimization depends on info updated by ValueNumber,
// but can generate dead code
pipe.addPass(new LoopSimplify());
// ValueNumber tends to generate most dead code
pipe.addPass(new DeadCodeEliminator());
if (iteration % 3 == 0) {
// Dead code eliminator will have just eliminated references
pipe.addPass(new DemoteGlobals());
}
// ValueNumber adds blocking vars to function
pipe.addPass(new FunctionSignature());
// Do this after forward dataflow to improve odds of fusing things
// one common subexpression elimination has happened
pipe.addPass(new ContinuationFusion());
// Can only run this pass once. Do it near end so that
// results can be cleaned up by forward dataflow
if (iteration == nIterations - (nIterations / 4) - 1) {
pipe.addPass(new Pipeline());
if (debug)
pipe.addPass(Validate.standardValidator());
}
// Expand ops about halfway through
boolean doInlineOps = iteration == nIterations / 2;
if (doInlineOps) {
pipe.addPass(new DataflowOpInline());
}
// Do merges near end since it can be detrimental to other optimizations
boolean doWaitMerges = (iteration >= nIterations - (nIterations / 4) - 2)
&& iteration % 2 == 0;
pipe.addPass(new WaitCoalescer(doWaitMerges, canReorder));
if (debug)
pipe.addPass(Validate.standardValidator());
pipe.runPipeline(logger, prog, iteration);
// Cleanup internal indices, etc.
prog.cleanup();
}
}
private static void postprocess(PrintStream icOutput, Logger logger,
boolean debug, Program prog, long nIterations) throws UserException {
OptimizerPipeline postprocess = new OptimizerPipeline(icOutput);
// Final dead code elimination to clean up any remaining dead code
// (from last iteration or constant sharing)
postprocess.addPass(new DeadCodeEliminator());
// Final pruning to remove unused functions
postprocess.addPass(new PruneFunctions());
// Add in all the variable passing annotations now that instructions,
// continuations and variables are fixed
postprocess.addPass(new FixupVariables());
// Add in reference counting after passing annotations
postprocess.addPass(new RefcountPass());
// Refcount pass sometimes adds instructions, do another fixup as a
// workaround to make sure that passing annotations are still correct
postprocess.addPass(new FixupVariables());
postprocess.addPass(Validate.finalValidator());
postprocess.runPipeline(logger, prog, nIterations - 1);
}
}
| 33.834746 | 79 | 0.675391 |
a882d223b958a82dfda9423d25c4fc5b5def99dc | 5,848 | package com.stackroute.innovatormanagementservice.service;
import com.stackroute.innovatormanagementservice.domain.Idea;
import com.stackroute.innovatormanagementservice.domain.ServiceProvider;
import com.stackroute.innovatormanagementservice.dto.IdeaDto;
import com.stackroute.innovatormanagementservice.exception.EmailIdAlreadyExistsException;
import com.stackroute.innovatormanagementservice.exception.IdeaNotFoundException;
import com.stackroute.innovatormanagementservice.repository.ManagementRepo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
@Service
public class ManagementServiceImpl implements ManagementService {
private ManagementRepo managementRepo;
private Idea newIdea;
private Idea ideaDto;
private RestTemplate restTemplate;
private ServiceProvider serviceProvider;
private RabbitTemplate rabbitTemplate;
private List<ServiceProvider> serviceProviderDto = new ArrayList<>();
@Value("${serviceProvider.url}")
String url;
String ideaRoutingKey;
@Value("${idea.url}")
String ideaUrl;
@Autowired
public ManagementServiceImpl(ManagementRepo managementRepo, Idea newIdea, ServiceProvider serviceProvider, Idea ideaDto,RestTemplate restTemplate,RabbitTemplate rabbitTemplate) {
this.managementRepo = managementRepo;
this.newIdea = newIdea;
this.serviceProvider = serviceProvider;
this.ideaDto= ideaDto;
this.restTemplate =restTemplate;
this.rabbitTemplate=rabbitTemplate;
}
@RabbitListener(queues = "${javainuse.management.queue}")
public void saveIdea(IdeaDto ideaDto) {
Idea fetchedIdea = new Idea();
fetchedIdea.setTitle(ideaDto.getTitle());
fetchedIdea.setDescription(ideaDto.getDescription());
fetchedIdea.setBudget(ideaDto.getBudget());
fetchedIdea.setDomain(ideaDto.getDomain());
fetchedIdea.setEmailId(ideaDto.getEmailId());
fetchedIdea.setRoles(ideaDto.getRoles());
fetchedIdea.setSubDomain(ideaDto.getSubDomain());
fetchedIdea.setTimestamp(ideaDto.getTimestamp());
fetchedIdea.setAppliedServiceProviders(ideaDto.getServiceProviders());
managementRepo.save(fetchedIdea);
}
//Method to update applied service provider to the list
@Override
public Idea updateIdea(String title, String emailId) throws IdeaNotFoundException , EmailIdAlreadyExistsException {
Idea recievedIdea = managementRepo.findByTitle(title);
if (recievedIdea == null) {
throw new IdeaNotFoundException("Idea Not found");
}
else {
serviceProvider = restTemplate.getForObject(url + emailId, ServiceProvider.class);
List<ServiceProvider> serviceProviderList = recievedIdea.getAppliedServiceProviders();
if(serviceProviderList == null){
serviceProviderList = new ArrayList<ServiceProvider>();
}
for(int i= 0; i<recievedIdea.getAppliedServiceProviderEmail().size();i++){
if((recievedIdea.getAppliedServiceProviderEmail().get(i)).equals(emailId)){
throw new EmailIdAlreadyExistsException("User Already Applied for this Idea");
}
}
recievedIdea.getAppliedServiceProviderEmail().add(emailId);
serviceProviderList.add(serviceProvider);
recievedIdea.setAppliedServiceProviders(serviceProviderList);
managementRepo.save(recievedIdea);
}
return recievedIdea;
}
@Override
public List<ServiceProvider> getAppliedServiceProviders(String title) throws IdeaNotFoundException {
List<ServiceProvider> appliedServiceProviders;
Idea recievedIdea = managementRepo.findByTitle(title);
if (recievedIdea == null) {
throw new IdeaNotFoundException("Idea Not found");
} else {
appliedServiceProviders = recievedIdea.getAppliedServiceProviders();
return appliedServiceProviders;
}
}
//deletes applied users
@Override
public Idea deleteAppliedServiceProvider(String title, String emailId, boolean status) throws Exception {
Idea newIdea1 = managementRepo.findByTitle(title);
Idea updatedIdea = new Idea();
List<ServiceProvider> serviceProviderList = new ArrayList<>();
serviceProviderList = newIdea1.getAppliedServiceProviders();
for (int i = 0; i < serviceProviderList.size(); i++) {
if ((serviceProviderList.get(i).getEmailId()).equals( emailId)) {
if (status == false) {
serviceProviderList.remove(i);
newIdea1.setAppliedServiceProviders(serviceProviderList);
updatedIdea = managementRepo.save(newIdea1);
return updatedIdea;
} else {
ideaDto.setTitle(title);
serviceProviderDto.add(serviceProviderList.get(i));
ideaDto.setAppliedServiceProviders(serviceProviderDto);
System.out.println(ideaUrl);
restTemplate.put(ideaUrl,ideaDto);
serviceProviderList.remove(i);
newIdea1.setAppliedServiceProviders(serviceProviderList);
updatedIdea = managementRepo.save(newIdea1);
return updatedIdea;
}
}
}
return updatedIdea;
}
}
| 43.641791 | 182 | 0.688269 |
8e102c3ad5562b561127e47c85cee55673ef36f4 | 3,200 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.jackrabbit.oak.benchmark;
import static javax.jcr.security.Privilege.JCR_READ;
import static org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils.addAccessControlEntry;
import javax.jcr.Node;
import javax.jcr.Session;
import org.apache.jackrabbit.oak.spi.security.principal.EveryonePrincipal;
/**
* {@code GetNodeTest} implements a performance test, which reads
* nodes from the repository. To determine the effect of access control
* evaluation the test can either run with anonymous or with admin.
*/
public abstract class GetNodeTest extends AbstractTest {
private final String name;
private Node testRoot;
public static Benchmark withAdmin() {
return new GetNodeTest("GetNodeWithAdmin") {
@Override
protected Session login() {
return loginWriter();
}
};
}
public static Benchmark withAnonymous() {
return new GetNodeTest("GetNodeWithAnonymous") {
@Override
protected Session login() {
return loginAnonymous();
}
};
}
protected GetNodeTest(String name) {
this.name = name;
}
protected abstract Session login();
@Override
public String toString() {
return name;
}
@Override
protected void beforeSuite() throws Exception {
Session session = loginWriter();
testRoot = session.getRootNode().addNode(
getClass().getSimpleName() + TEST_ID, "nt:unstructured");
testRoot.addNode("node1").addNode("node2");
addAccessControlEntry(session, testRoot.getPath(), EveryonePrincipal.getInstance(),
new String[] {JCR_READ}, true);
session.save();
testRoot = login().getNode(testRoot.getPath());
session.logout();
}
@Override
protected void runTest() throws Exception {
for (int i = 0; i < 10000; i++) {
testRoot.getNode("node1").getNode("node2");
testRoot.getNode("node1/node2");
testRoot.hasNode("node-does-not-exist");
}
}
@Override
protected void afterSuite() throws Exception {
Session session = loginWriter();
session.getNode(testRoot.getPath()).remove();
testRoot.getSession().logout();
session.save();
session.logout();
}
}
| 31.683168 | 110 | 0.662188 |
1ea213cff6e5d888f1ff8e92e07d7475b6035c7f | 84 | /** <p>Classes that provide networking functionality.</p> */
package io.auklet.net;
| 28 | 60 | 0.72619 |
8b39db19696724c644ef476b28c954ed5c9273af | 1,692 | package com.xinonix.hl7.fhir.stu3;
import com.google.gson.annotations.Expose;
/**
* A collection of documents compiled for a purpose together with metadata that applies to the collection.
*/
public class DocumentManifestContent extends BackboneElement {
@Expose
private Attachment pAttachment;
/**
* Getter for pAttachment
* @return The list of references to document content, or Attachment that consist of the parts of this document manifest. Usually, these would be document references, but direct references to Media or Attachments are also allowed.
*/
public Attachment getPAttachment() { return pAttachment; }
/**
* Setter for pAttachment
* @param value The list of references to document content, or Attachment that consist of the parts of this document manifest. Usually, these would be document references, but direct references to Media or Attachments are also allowed.
*/
public void setPAttachment(Attachment value) { pAttachment = value; }
@Expose
private Reference pReference;
/**
* Getter for pReference
* @return The list of references to document content, or Attachment that consist of the parts of this document manifest. Usually, these would be document references, but direct references to Media or Attachments are also allowed.
*/
public Reference getPReference() { return pReference; }
/**
* Setter for pReference
* @param value The list of references to document content, or Attachment that consist of the parts of this document manifest. Usually, these would be document references, but direct references to Media or Attachments are also allowed.
*/
public void setPReference(Reference value) { pReference = value; }
}
| 38.454545 | 236 | 0.771277 |
a96d6901f844bc7a750fa7eb07e7bc5af17735b2 | 816 | package com.softicar.sqml.ui.contentassist;
import com.softicar.platform.common.code.java.JavaIdentifier;
import com.softicar.platform.common.code.java.WordFragment;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class PossibleVariableNamesGenerator {
private final List<WordFragment> wordFragments;
public PossibleVariableNamesGenerator(List<WordFragment> wordFragments) {
this.wordFragments = wordFragments;
}
public List<String> generate() {
int size = wordFragments.size();
List<String> possibleNames = new ArrayList<>();
for (int i = 0; i < size; ++i) {
List<WordFragment> fragments = wordFragments.subList(i, size);
possibleNames.add(new JavaIdentifier(fragments).asParameter());
}
Collections.reverse(possibleNames);
return possibleNames;
}
}
| 27.2 | 74 | 0.769608 |
b8923b7d6ee5f91018a5952e674fa2df65073659 | 1,307 | package minium.developer.web.version;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import minium.developer.utils.HttpClientUtils;
public class GitHubRelease extends MiniumReleaseManager {
protected static final String GITHUB_OWNER = "viltgroup";
protected static final String GITHUB_REPOSITORY = "minium-developer";
protected static final String GITHUB_RELEASES_ALL = "https://api.github.com/repos/{owner}/{repository}/releases";
public GitHubRelease(HttpClientUtils httpClient) {
super(httpClient);
}
@Override
public Release getLastRelease() throws IOException {
List<Release> latest = getLatest();
return (!latest.isEmpty() && latest != null) ? latest.get(0) : null;
}
private List<Release> getLatest() throws IOException {
ArrayList<Release> releases = new ArrayList<>();
String apiUrl = getAllReleasesString();
String response = httpClient.simpleRequest(apiUrl);
releases.addAll(Arrays.asList(objectMapper.readValue(response, Release[].class)));
return releases;
}
private String getAllReleasesString() {
return GITHUB_RELEASES_ALL.replace("{owner}", GITHUB_OWNER).replace("{repository}", GITHUB_REPOSITORY);
}
}
| 32.675 | 117 | 0.715379 |
c86bb5103905141236b2a0da50a146c22150a2b7 | 1,326 | package com.bazaarvoice.emodb.blob.db.astyanax;
import com.bazaarvoice.emodb.common.cassandra.CassandraKeyspace;
import com.bazaarvoice.emodb.table.db.astyanax.Placement;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.Composite;
import java.nio.ByteBuffer;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A Cassandra keyspace and the BlobStore column family.
*/
class BlobPlacement implements Placement {
private final String _name;
private final CassandraKeyspace _keyspace;
private final ColumnFamily<ByteBuffer, Composite> _blobColumnFamily;
BlobPlacement(String name,
CassandraKeyspace keyspace,
ColumnFamily<ByteBuffer, Composite> blobColumnFamily) {
_name = checkNotNull(name, "name");
_keyspace = checkNotNull(keyspace, "keyspace");
_blobColumnFamily = checkNotNull(blobColumnFamily, "blobColumnFamily");
}
@Override
public String getName() {
return _name;
}
@Override
public CassandraKeyspace getKeyspace() {
return _keyspace;
}
ColumnFamily<ByteBuffer, Composite> getBlobColumnFamily() {
return _blobColumnFamily;
}
// for debugging
@Override
public String toString() {
return _name;
}
}
| 27.625 | 79 | 0.711916 |
8cb98aab32a65f47dbf1bb74c91f69fb41ebd355 | 79 | package Factory.FactoryMethod;
public interface LipStick {
void show();
}
| 13.166667 | 30 | 0.734177 |
a6c4a1a3635f669d291ec5d14a47abfabd186f6d | 3,713 | package fr.max2.annotated.processor.network.coder;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import fr.max2.annotated.api.processor.network.DataProperties;
import fr.max2.annotated.processor.network.coder.handler.IHandlerProvider;
import fr.max2.annotated.processor.network.coder.handler.NamedDataHandler;
import fr.max2.annotated.processor.network.model.IPacketBuilder;
import fr.max2.annotated.processor.utils.ClassRef;
import fr.max2.annotated.processor.utils.ProcessingTools;
import fr.max2.annotated.processor.utils.PropertyMap;
import fr.max2.annotated.processor.utils.exceptions.IncompatibleTypeException;
import fr.max2.annotated.processor.utils.exceptions.CoderExcepetion;
public class SerializableCoder extends DataCoder
{
public static final IHandlerProvider NBT_SERIALIZABLE = NamedDataHandler.provider(ClassRef.NBT_SERIALIZABLE_INTERFACE, SerializableCoder::new);
private final TypeMirror nbtType, implType;
private final DataCoder nbtCoder;
public SerializableCoder(ProcessingTools tools, String uniqueName, TypeMirror paramType, PropertyMap properties) throws CoderExcepetion
{
super(tools, uniqueName, paramType, properties);
String typeName = ClassRef.NBT_SERIALIZABLE_INTERFACE;
TypeMirror serializableType = tools.elements.getTypeElement(typeName).asType();
DeclaredType serialisableType = tools.types.refineTo(paramType, serializableType);
if (serialisableType == null) throw new IncompatibleTypeException("The type '" + paramType + "' is not a sub type of " + typeName);
this.nbtType = serialisableType.getTypeArguments().get(0);
this.nbtCoder = tools.coders.getCoder(uniqueName + "Data", this.nbtType, properties.getSubPropertiesOrEmpty("nbt"));
String implName = properties.getValueOrEmpty("impl");
TypeMirror implType = paramType;
if (!implName.isEmpty())
{
TypeElement elem = tools.elements.getTypeElement(implName);
if (elem == null)
throw new IncompatibleTypeException("Unknown type '" + implName + "' as implementation for " + ClassRef.NBT_SERIALIZABLE_INTERFACE);
implType = elem.asType();
DeclaredType refinedImpl = tools.types.refineTo(implType, serializableType);
if (refinedImpl == null)
throw new IncompatibleTypeException("The type '" + implName + "' is not a sub type of " + ClassRef.NBT_SERIALIZABLE_INTERFACE);
TypeMirror implNbtType = refinedImpl.getTypeArguments().get(0);
DeclaredType revisedImplType = tools.types.replaceTypeArgument((DeclaredType)implType, implNbtType, this.nbtType);
if (!tools.types.isAssignable(revisedImplType, this.internalType))
throw new IncompatibleTypeException("The type '" + implName + "' is not a sub type of '" + this.internalType + "'");
}
this.implType = implType;
requireDefaultConstructor(tools.types, this.implType, "Use the " + DataProperties.class.getCanonicalName() + " annotation with the 'impl' property to specify a valid implementation");
}
@Override
public OutputExpressions addInstructions(IPacketBuilder builder, String saveAccessExpr, String internalAccessExpr, String externalAccessExpr)
{
tools.types.provideTypeImports(this.nbtType, builder);
builder.decoder().add(this.tools.naming.computeFullName(this.paramType) + " " + this.uniqueName + " = new " + this.tools.naming.computeSimplifiedName(this.implType) + "();");
OutputExpressions nbtOutput = builder.runCoderWithoutConversion(this.nbtCoder, saveAccessExpr + ".serializeNBT()");
builder.decoder().add(this.uniqueName + ".deserializeNBT(" + nbtOutput.decoded + ");");
return new OutputExpressions(this.uniqueName, internalAccessExpr, externalAccessExpr);
}
}
| 50.863014 | 185 | 0.784541 |
ff3e876160526d9a0c086ffe9a8bd68030cfbdc1 | 1,067 | package com.github.syuchan1005.npmscriptrunner;
import com.intellij.execution.lineMarker.ExecutorAction;
import com.intellij.execution.lineMarker.RunLineMarkerContributor;
import com.intellij.icons.AllIcons;
import com.intellij.json.psi.JsonProperty;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class NpmRunLineMarkerContributor extends RunLineMarkerContributor {
@Nullable
@Override
public Info getInfo(@NotNull PsiElement psiElement) {
if (psiElement instanceof JsonProperty) {
PsiElement parent = psiElement.getParent().getParent();
if (parent instanceof JsonProperty && ((JsonProperty) parent).getName().equals("scripts")) {
String text = psiElement.getFirstChild().getText();
final String script = text.substring(1, text.length() - 1);
return new Info(AllIcons.General.Run,
(element) -> "Run '" + script + "'\nDebug '" + script + "'",
ExecutorAction.getActions());
}
}
return null;
}
public static void main(String[] args) {
}
}
| 33.34375 | 95 | 0.750703 |
315ace0693b819c0a890e248c1d805351d4bbcb8 | 3,216 | package com.solomatoff.mvc.model.store.memorystore;
import com.solomatoff.mvc.controller.CommonTest;
import com.solomatoff.mvc.controller.Controller;
import com.solomatoff.mvc.entities.User;
import com.solomatoff.mvc.model.PersistentDAO;
import com.solomatoff.mvc.model.store.MemoryStore;
import org.junit.Before;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
public class UserMemoryStoreTest {
private static final PersistentDAO STORE = MemoryStore.getInstance();
@Before
public void setUp() {
CommonTest.clearAndCreateDataInMemory();
}
@Test
public void addUser() {
User user7 = new User(7, "user7", "login7", "password", "email7", new Timestamp(System.currentTimeMillis()));
List<User> expected = new ArrayList<>();
expected.add(user7);
// Добавляем первый раз User7
List<User> result = STORE.addUser(user7);
assertThat(result, is(expected));
// Добавляем второй раз User7, теперь список должен быть пустой, т.к. User второй раз не добавится
result = STORE.addUser(user7);
assertThat(result.size(), is(0));
}
@Test
public void updateUser() {
User user = new User();
user.setId(6);
List<User> expected = STORE.findByIdUser(user);
// Обновим User с id=6
User newUser6 = new User(6, "newuser6", "newlogin6", "password", "newemail6", new Timestamp(System.currentTimeMillis()));
List<User> result = STORE.updateUser(newUser6);
assertThat(result.get(0).getName(), is(expected.get(0).getName()));
}
@Test
public void deleteUser() {
User user = new User();
user.setId(6);
List<User> expected = STORE.findByIdUser(user);
// Удалим User с id = 6
List<User> result = STORE.deleteUser(user);
assertThat(result.get(0).getName(), is(expected.get(0).getName()));
// Попытаемся удалить не существующий User
user = new User();
user.setId(8);
result = STORE.deleteUser(user);
assertThat(result.size(), is(0));
}
@Test
public void findByIdUser() {
User user4 = new User(4, "user4", "login4", "password", "email4", new Timestamp(System.currentTimeMillis()));
User result = STORE.findByIdUser(user4).get(0);
assertThat(result.getName(), is(user4.getName()));
}
@Test
public void findAllUsers() {
List<User> expected = new ArrayList<>();
User user = new User();
user.setId(4);
User user4 = STORE.findByIdUser(user).get(0);
expected.add(user4);
user = new User();
user.setId(5);
User user5 = STORE.findByIdUser(user).get(0);
expected.add(user5);
user = new User();
user.setId(6);
User user6 = STORE.findByIdUser(user).get(0);
expected.add(user6);
List<User> result = STORE.findAllUsers(user);
int i = 0;
for (User userloop : result) {
assertThat(userloop.getName(), is(expected.get(i).getName()));
i++;
}
}
} | 32.484848 | 129 | 0.625 |
618901a1511a590ee3ef58eb9c857759592edfd6 | 404 | package com.codernauti.sweetie.pairing;
interface PairingContract {
interface View {
void setPresenter(PairingContract.Presenter presenter);
void showMessage(String message);
void showLoadingProgress();
void hideLoadingProgress();
void startDashboardActivity();
}
interface Presenter {
void sendPairingRequest(String partnerPhone);
}
}
| 22.444444 | 63 | 0.688119 |
b9b212906c4a5f1367d41e2291aeb18041de1e88 | 2,307 | package org.patientview.builder;
import org.apache.commons.lang.StringUtils;
import org.hl7.fhir.instance.model.CodeableConcept;
import org.hl7.fhir.instance.model.Procedure;
import org.hl7.fhir.instance.model.ResourceReference;
import org.patientview.config.utils.CommonUtils;
import org.patientview.persistence.model.FhirProcedure;
/**
* Build Procedure object, suitable for insertion/update into FHIR. Handles update and create, with assumption that
* empty strings means clear existing data, null strings means leave alone and do not update. For Date, clear if null.
*
* Created by jamesr@solidstategroup.com
* Created on 21/03/2016
*/
public class ProcedureBuilder {
private Procedure procedure;
private FhirProcedure fhirProcedure;
private ResourceReference patientReference;
private ResourceReference encounterReference;
public ProcedureBuilder(Procedure procedure, FhirProcedure fhirProcedure,
ResourceReference patientReference, ResourceReference encounterReference) {
this.procedure = procedure;
this.fhirProcedure = fhirProcedure;
this.patientReference = patientReference;
this.encounterReference = encounterReference;
}
public Procedure build() {
if (procedure == null) {
procedure = new Procedure();
}
procedure.setSubject(patientReference);
procedure.setEncounter(encounterReference);
// body site
if (fhirProcedure.getBodySite() != null) {
procedure.getBodySite().clear();
if (StringUtils.isNotEmpty(fhirProcedure.getBodySite())) {
CodeableConcept bodySite = new CodeableConcept();
bodySite.setTextSimple(CommonUtils.cleanSql(fhirProcedure.getBodySite()));
procedure.getBodySite().add(bodySite);
}
}
// type
if (fhirProcedure.getType() != null) {
if (StringUtils.isNotEmpty(fhirProcedure.getType())) {
CodeableConcept type = new CodeableConcept();
type.setTextSimple(CommonUtils.cleanSql(fhirProcedure.getType()));
procedure.setType(type);
} else {
procedure.setType(null);
}
}
return procedure;
}
}
| 35.492308 | 118 | 0.671868 |
35cb7c885a4cf7f0845b5f4b1b2a6ae1edb4ac38 | 11,186 | /*
* MIT Licence
* Copyright (c) 2021 Simon Frankenberger
*
* Please see LICENCE.md for complete licence text.
*/
package eu.fraho.spring.securityJwt.memcache.service;
import eu.fraho.spring.securityJwt.base.config.RefreshProperties;
import eu.fraho.spring.securityJwt.base.dto.JwtUser;
import eu.fraho.spring.securityJwt.base.dto.RefreshToken;
import eu.fraho.spring.securityJwt.base.exceptions.RefreshException;
import eu.fraho.spring.securityJwt.base.service.RefreshTokenStore;
import eu.fraho.spring.securityJwt.memcache.config.MemcacheProperties;
import eu.fraho.spring.securityJwt.memcache.dto.LruMetadumpEntry;
import eu.fraho.spring.securityJwt.memcache.dto.MemcacheEntry;
import eu.fraho.spring.securityJwt.memcache.exceptions.RequestTimedOutException;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.internal.OperationFuture;
import net.spy.memcached.ops.OperationStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@SuppressWarnings("SpringJavaAutowiredMembersInspection")
@Slf4j
@NoArgsConstructor
public class MemcacheTokenStore implements RefreshTokenStore {
private RefreshProperties refreshProperties;
private MemcacheProperties memcacheProperties;
private UserDetailsService userDetailsService;
private MemcachedClient memcachedClient;
private boolean lruCrawlerAvailable;
@Override
public void saveToken(JwtUser user, String token) {
String key = memcacheProperties.getPrefix() + token;
String entry = MemcacheEntry.from(user).toString();
OperationFuture<Boolean> future = getAndWait("Error while saving refresh token on memcache server", () ->
memcachedClient.set(key, (int) refreshProperties.getExpiration().toSeconds(), entry)
);
if (!future.getStatus().isSuccess()) {
throw new RefreshException("Could not save the token, memcached responded with '!Status.isSuccess()': " + future.getStatus().getMessage());
}
}
@Override
@SuppressWarnings("unchecked")
public <T extends JwtUser> Optional<T> useToken(String token) {
String key = memcacheProperties.getPrefix() + token;
// will be "null" if invalid token
Object found = memcachedClient.get(key);
Optional<T> result = Optional.empty();
if (found != null) {
String username = MemcacheEntry.from((String) found).getUsername();
result = Optional.ofNullable((T) userDetailsService.loadUserByUsername(username));
}
if (!getAndWait("Error while removing refresh token on memcache server", () -> memcachedClient.delete(key)).getStatus().isSuccess()) {
result = Optional.empty();
}
return result;
}
@Override
public List<RefreshToken> listTokens(JwtUser user) {
return listTokens().getOrDefault(user.getId(), Collections.emptyList());
}
@Override
public Map<Long, List<RefreshToken>> listTokens() {
Map<Long, List<RefreshToken>> result = new HashMap<>();
List<String> keys = listAllKeys();
Map<String, Object> entries = memcachedClient.getBulk(keys);
int prefixLen = memcacheProperties.getPrefix().length();
for (Map.Entry<String, Object> entry : entries.entrySet()) {
MemcacheEntry dto = MemcacheEntry.from((String) entry.getValue());
int expiresIn = -1;
String token = entry.getKey().substring(prefixLen);
result.computeIfAbsent(dto.getId(), s -> new ArrayList<>()).add(
RefreshToken.builder()
.token(token)
.expiresIn(expiresIn).build()
);
}
result.replaceAll((s, t) -> Collections.unmodifiableList(t));
return Collections.unmodifiableMap(result);
}
@Override
public boolean revokeToken(String token) {
String key = memcacheProperties.getPrefix() + token;
return getAndWait("Error while revoking refresh token on memcache server", () ->
memcachedClient.delete(key)).getStatus().isSuccess();
}
@Override
public int revokeTokens(JwtUser user) {
List<String> allKeys = listAllKeys();
Map<String, Object> entries = memcachedClient.getBulk(allKeys);
List<OperationFuture<Boolean>> futures = new ArrayList<>();
for (Map.Entry<String, Object> entry : entries.entrySet()) {
MemcacheEntry dto = MemcacheEntry.from((String) entry.getValue());
if (Objects.equals(dto.getId(), user.getId())) {
futures.add(memcachedClient.delete(entry.getKey()));
}
}
return submitAndCountSuccess(allKeys, futures);
}
@Override
public int revokeTokens() {
List<String> keys = listAllKeys();
List<OperationFuture<Boolean>> futures = new ArrayList<>();
for (String key : keys) {
futures.add(memcachedClient.delete(key));
}
return submitAndCountSuccess(keys, futures);
}
@Override
public void afterPropertiesSet() throws IOException {
log.info("Using memcache implementation to handle refresh tokens");
if (refreshProperties.getExpiration().toSeconds() > 2_592_000) {
throw new IllegalStateException("Refresh expiration may not exceed 30 days when using memcached");
}
log.info("Starting memcache connection to {}:{}", memcacheProperties.getHost(), memcacheProperties.getPort());
InetSocketAddress address = new InetSocketAddress(memcacheProperties.getHost(), memcacheProperties.getPort());
memcachedClient = new MemcachedClient(address);
String version = memcachedClient.getVersions().get(address);
String[] parts = version.split("\\.", 3);
lruCrawlerAvailable = Integer.parseInt(parts[0]) > 1 || (Integer.parseInt(parts[0]) == 1 && Integer.parseInt(parts[1]) >= 5);
}
@Autowired
public void setRefreshProperties(@NonNull RefreshProperties refreshProperties) {
this.refreshProperties = refreshProperties;
}
@Autowired
public void setMemcacheProperties(@NonNull MemcacheProperties memcacheProperties) {
this.memcacheProperties = memcacheProperties;
}
@Autowired
public void setUserDetailsService(@NonNull UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
protected OperationFuture<Boolean> getAndWait(String message, Supplier<OperationFuture<Boolean>> action) {
try {
OperationFuture<Boolean> future = action.get();
future.get(memcacheProperties.getTimeout(), TimeUnit.SECONDS);
return future;
} catch (TimeoutException | InterruptedException | ExecutionException e) {
throw new RefreshException(message, e);
}
}
protected List<String> listAllKeys() {
if (lruCrawlerAvailable) {
return listAllKeysModern();
} else {
return listAllKeysLegacy();
}
}
protected List<String> listAllKeysModern() {
Map<SocketAddress, List<LruMetadumpEntry>> entries = getLruCrawlerMetadump();
return entries.values().stream()
.flatMap(List::stream)
.map(LruMetadumpEntry::getKey)
.filter(e -> e.startsWith(memcacheProperties.getPrefix()))
.collect(Collectors.toList());
}
protected Map<SocketAddress, List<LruMetadumpEntry>> getLruCrawlerMetadump() {
Map<SocketAddress, List<LruMetadumpEntry>> result = new HashMap<>();
CountDownLatch blatch = memcachedClient.broadcastOp((n, latch) -> {
SocketAddress sa = n.getSocketAddress();
ArrayList<LruMetadumpEntry> list = new ArrayList<>();
result.put(sa, list);
return new LruCrawlerMetadumpOperationImpl("all", new LruCrawlerMetadumpOperation.Callback() {
@Override
public void gotMetadump(LruMetadumpEntry entry) {
list.add(entry);
}
@Override
@SuppressWarnings("synthetic-access")
public void receivedStatus(OperationStatus status) {
if (!status.isSuccess()) {
log.error("Unsuccessful lru_crawler metadump: " + status);
}
}
@Override
public void complete() {
latch.countDown();
}
});
});
try {
if (!blatch.await(memcacheProperties.getTimeout(), TimeUnit.SECONDS)) {
throw new RequestTimedOutException("lru_crawler metadump timed out");
}
} catch (InterruptedException e) {
throw new RequestTimedOutException("Interrupted waiting for lru_crawler metadump", e);
}
return result;
}
protected List<String> listAllKeysLegacy() {
List<String> result = new ArrayList<>();
Set<Integer> slabs = memcachedClient.getStats("items")
.entrySet().iterator().next()
.getValue().keySet().stream()
.filter(k -> k.matches("^items:[0-9]+:number$"))
.map(s -> s.split(":")[1])
.map(Integer::valueOf)
.collect(Collectors.toSet());
for (Integer slab : slabs) {
int used_chunks = Integer.parseInt(
memcachedClient.getStats("slabs " + slab)
.entrySet().iterator().next()
.getValue().get(slab + ":used_chunks"));
Set<String> entries = memcachedClient.getStats("cachedump " + slab + " " + used_chunks)
.entrySet().iterator().next().getValue().keySet()
.stream().filter(e -> e.startsWith(memcacheProperties.getPrefix()))
.collect(Collectors.toSet());
result.addAll(entries);
}
return Collections.unmodifiableList(result);
}
protected int submitAndCountSuccess(List<String> keys, List<OperationFuture<Boolean>> futures) {
int count = keys.size();
for (OperationFuture<Boolean> future : futures) {
if (!getAndWait("Error while revoking tokens on memcache server", () -> future).getStatus().isSuccess()) {
count--;
}
}
return count;
}
}
| 40.824818 | 151 | 0.646791 |
992fb4d58dba9de22a5ecaa50d7d77b24e181c7f | 3,660 | package com.tc.controller;
import com.alibaba.fastjson.JSON;
import com.tc.domain.Problem;
import com.tc.service.ProblemService;
import com.tc.utils.Result;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping(value = "/problem")
public class ProblemController {
@Autowired
private ProblemService problemService;
@RequestMapping(value = "/searchProblem", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
public String searchProblem(HttpServletRequest request) {
String problemId = request.getParameter("problemId");
if (problemId.isEmpty()) {
return JSON.toJSON(new Result(false, "输入题目号为空")).toString();
} else {
Result result = problemService.findProblemById(problemId);
return JSON.toJSON(result).toString();
}
}
@RequestMapping(value = "/add", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public String add(HttpServletRequest request,
@RequestParam("title") String title,
@RequestParam("discription") String discription,
@RequestParam("inputData") String inputData,
@RequestParam("outputData") String outputData,
@RequestParam("example") String example,
@RequestParam("testData") String testData) throws Exception {
Problem problem = new Problem();
problem.setTitle(title);
problem.setDiscription(discription);
problem.setInputData(inputData);
problem.setOutputData(outputData);
problem.setExample(example);
problem.setTestData(testData);
problem.setCommit(0);
problem.setPass(0);
Result result = problemService.addProblem(problem);
return JSON.toJSON(result).toString();
}
@RequestMapping(value = "/getProblems", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
public String getProblems(HttpServletRequest request) throws Exception {
int page = Integer.parseInt(request.getParameter("pageNum"));
int problemsNum = Integer.parseInt(request.getParameter("problemsNum"));
Result result = problemService.findProblemsByPage(page, problemsNum);
return JSON.toJSON(result).toString();
}
@RequestMapping(value = "/showDetailedProblem", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
public String showDetailedProblem(HttpServletRequest request) throws Exception {
String problemId = request.getParameter("problemId");
Result result = problemService.findProblemById(problemId);
return JSON.toJSON(result).toString();
}
@RequestMapping(value = "/delete", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public String delete(HttpServletRequest request) throws Exception {
String problemId = request.getParameter("problemId");
int id = Integer.parseInt(problemId);
Result result = problemService.deleteProblemById(id);
return JSON.toJSON(result).toString();
}
@RequestMapping(value = "/getCount", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
public String getCount() {
Result result = problemService.findProblemCount();
return JSON.toJSON(result).toString();
}
}
| 43.571429 | 117 | 0.691803 |
d1ff802d65efc03e05608c8cb294b22d416c9e84 | 3,002 | package Chapter12.exercise17;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Hangman {
public static void main(String[] args) throws FileNotFoundException {
game();
}
public static void game() throws FileNotFoundException{
File file = new File("src/Chapter12/exercise17/hangman.txt");
Scanner input = new Scanner(file);
ArrayList<String> wordlist = new ArrayList<String>();
while (input.hasNext()) {
String word = input.next();
wordlist.add(word);
}
input.close();
boolean isGameOver = false;
char[] choosenWord = pickARandomWord(wordlist).toCharArray();
char[] asterisk = new char[choosenWord.length];
for (int i = 0; i < asterisk.length; i++) {
asterisk[i] = '*';
}
int missedCounter = 0;
Scanner scan = new Scanner(System.in);
while (!isGameOver) {
System.out.println("Enter a letter in word ");
printCharArray(asterisk);
char getLetter = scan.next().charAt(0);
if (isLetterInChoosenWord(getLetter, choosenWord)) {
updateAsterisk(choosenWord, asterisk, getLetter);
} else {
missedCounter++;
}
isGameOver = checkAllLetterFound(asterisk);
if (isGameOver) {
printAfterGameOver(missedCounter, choosenWord);
System.out.println("Do you want another game?");
char answer = scan.next().charAt(0);
isGameOver = anotherGame(answer);
choosenWord = pickARandomWord(wordlist).toCharArray();
asterisk = new char[choosenWord.length];
for (int i = 0; i < asterisk.length; i++) {
asterisk[i] = '*';
}
missedCounter = 0;
}
}
scan.close();
}
public static boolean anotherGame( char answer) {
if (answer == 'y' || answer == 'Y') {
return false;
}else {
return true;
}
}
public static void printAfterGameOver(int missedCounter, char[] choosenWord) {
System.out.print("The word is ");
printCharArray(choosenWord);
System.out.println(".You missed " + missedCounter + " time");
}
public static boolean checkAllLetterFound(char[] asterisk) {
for (int i = 0; i < asterisk.length; i++) {
if (asterisk[i] == '*') {
return false;
}
}
return true;
}
public static void updateAsterisk(char[] choosenWord, char[] asterisk, char letter) {
for (int i = 0; i < choosenWord.length; i++) {
if (choosenWord[i] == letter) {
asterisk[i] = letter;
}
}
}
public static boolean isLetterInChoosenWord(char letter, char[] choosenWord) {
for (int i = 0; i < choosenWord.length; i++) {
if (choosenWord[i] == letter) {
return true;
}
}
return false;
}
public static String pickARandomWord(ArrayList<String> wordsArray) {
int randomIndex = (int) (Math.random() * wordsArray.size());
return wordsArray.get(randomIndex);
}
public static void printCharArray(char[] asteriskArray) {
for (int i = 0; i < asteriskArray.length; i++) {
System.out.print(asteriskArray[i]);
}
}
}
| 20.147651 | 86 | 0.651566 |
6c10009d392f3fbb9b8a6ab4ee249424d3bb5add | 2,967 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.fakeadbserver.hostcommandhandlers;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.fakeadbserver.DeviceState;
import com.android.fakeadbserver.FakeAdbServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
* host:devices is a one-shot command to list devices and their states that are presently connected
* to the server.
*/
public class ListDevicesCommandHandler extends HostCommandHandler {
@NonNull public static final String COMMAND = "devices";
@NonNull
static String formatDeviceList(@NonNull List<DeviceState> deviceList) {
StringBuilder builder = new StringBuilder();
for (DeviceState deviceState : deviceList) {
builder.append(deviceState.getDeviceId());
builder.append("\t");
builder.append(deviceState.getDeviceStatus().getState());
builder.append("\n");
}
if (!deviceList.isEmpty()) {
builder.deleteCharAt(builder.length() - 1);
}
return builder.toString();
}
@Override
public boolean invoke(
@NonNull FakeAdbServer fakeAdbServer,
@NonNull Socket responseSocket,
@Nullable DeviceState device,
@NonNull String args) {
OutputStream stream;
try {
stream = responseSocket.getOutputStream();
} catch (IOException ignored) {
return false;
}
try {
String deviceListString = formatDeviceList(fakeAdbServer.getDeviceListCopy().get());
try {
writeOkay(stream); // Send ok first.
write4ByteHexIntString(stream, deviceListString.length());
stream.write(deviceListString.getBytes(StandardCharsets.US_ASCII));
} catch (IOException ignored) {
return false;
}
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
writeFailResponse(stream, "Failed to retrieve the list of devices from the server.");
return false;
}
return true;
}
}
| 34.5 | 99 | 0.665319 |
8368e54fa056017d8fb93d6cfd2bfbe0e2b1d21a | 2,908 | /*
* Copyright (c) 2017 - 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.sema4g.example.servlet;
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanCodex;
import com.google.web.bindery.autobean.shared.AutoBeanFactory;
import com.google.web.bindery.autobean.shared.AutoBeanUtils;
import com.google.web.bindery.autobean.vm.AutoBeanFactorySource;
import de.gishmo.gwt.sema4g.example.shared.dto.Message;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@SuppressWarnings("serial")
public class JsonMessageServlet
extends HttpServlet {
private MyBeanFactory myBeanFactory = AutoBeanFactorySource.create(MyBeanFactory.class);
interface MyBeanFactory
extends AutoBeanFactory {
AutoBean<Message> message();
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String wait = request.getParameter("wait");
if (wait != null) {
try {
Thread.sleep(Integer.parseInt(wait));
Message message = this.createMessage();
message.setMessage("Service (Servlet) Fourteen returned after " + wait + " ms");
PrintWriter out = response.getWriter();
out.print(this.serializeMessageToJSON(message));
out.flush();
return;
} catch (InterruptedException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
super.doPost(request,
response);
this.doGet(request,
response);
}
private Message createMessage() {
AutoBean<Message> message = myBeanFactory.message();
return message.as();
}
private String serializeMessageToJSON(Message message) {
AutoBean<Message> bean = AutoBeanUtils.getAutoBean(message);
return AutoBeanCodex.encode(bean)
.getPayload();
}
} | 31.956044 | 90 | 0.720426 |
482a9411b3c0a696bcd49af4f9b92ea49eced817 | 2,957 | /**
* Copyright (C) 2017+ furplag (https://github.com/furplag)
*
* 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 jp.furplag.time;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.lang.reflect.Constructor;
import java.time.Instant;
import org.junit.Test;
public class JulianDayNumberTest {
@SuppressWarnings("deprecation")
@Test
public void test() throws ReflectiveOperationException, SecurityException {
Constructor<JulianDayNumber> c = JulianDayNumber.class.getDeclaredConstructor();
c.setAccessible(true);
assertThat(c.newInstance() instanceof JulianDayNumber, is(true));
assertThat(JulianDayNumber.ofJulian(Millis.epoch), is(JulianDayNumber.ofEpochMilli(0)));
assertThat(JulianDayNumber.ofEpochDay(0), is(JulianDayNumber.ofEpochMilli(0)));
assertThat(JulianDayNumber.ofEpochMilli(Instant.parse("1999-01-01T00:00:00.000Z").toEpochMilli()), is(JulianDayNumber.ofEpochMilli(Instant.parse("1999-01-01T23:59:59.999Z").toEpochMilli())));
}
@SuppressWarnings("deprecation")
@Test
public void testOfEpochMillis() {
assertThat(JulianDayNumber.ofEpochMilli(0), is(((long)(Millis.epoch + .5d))));
assertThat(JulianDayNumber.ofEpochMilli(Millis.epochOfJulian), is(0L));
}
@SuppressWarnings("deprecation")
@Test
public void testOfJulian() {
assertThat(JulianDayNumber.ofJulian(0), is(0L));
assertThat(JulianDayNumber.ofJulian(Millis.epoch), is(2440_588L));
}
@SuppressWarnings("deprecation")
@Test
public void testOfModifiedJulian() {
assertThat(JulianDayNumber.ofModifiedJulian(0), is(2400_001L));
assertThat(JulianDayNumber.ofModifiedJulian(40587.5d), is(2440_588L));
}
@SuppressWarnings("deprecation")
@Test
public void testOfEpochDay() {
assertThat(JulianDayNumber.ofEpochDay(0), is(2440_588L));
assertThat(JulianDayNumber.ofEpochDay(Millis.toEpochDay(Instant.parse("2000-01-01T00:00:00.000Z").toEpochMilli())), is(((long) (Julian.ofEpochMilli(Instant.parse("2000-01-01T00:00:00.000Z").toEpochMilli()) + .5d))));
}
@SuppressWarnings("deprecation")
@Test
public void testToInstant() {
assertThat(JulianDayNumber.toInstant(0), is(Instant.parse("-4713-11-24T00:00:00.000Z")));
assertThat(JulianDayNumber.toInstant(2400_001), is(Instant.parse("1858-11-17T00:00:00.000Z")));
assertThat(JulianDayNumber.toInstant(2440_588), is(Instant.parse("1970-01-01T00:00:00.000Z")));
}
}
| 38.402597 | 220 | 0.743659 |
9c596c04934016eade50c2836de8beb93caea7ca | 1,827 | /*
* Copyright 2018 Jobsz(zhucongqi.cn)
*
* 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 cn.zhucongqi.oauth2.validators;
import cn.zhucongqi.oauth2.base.response.types.ResponseType;
import cn.zhucongqi.oauth2.base.validator.OAuthValidator;
import cn.zhucongqi.oauth2.consts.OAuthConsts;
import cn.zhucongqi.oauth2.request.OAuthHttpServletRequest;
/**
*
GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
Host: server.example.com
* @author Jobsz [zcq@zhucongqi.cn]
*/
public class AuthorizationRequestValidator extends OAuthValidator {
private static final long serialVersionUID = 6252782875378381870L;
public AuthorizationRequestValidator(OAuthHttpServletRequest request) {
super(request);
}
@Override
public void initParamDefaultValues() {
this.paramDefaultValues.put(OAuthConsts.OAuth.OAUTH_RESPONSE_TYPE, ResponseType.CODE.toString());
//clientid in OAuthClientCredentials logic validate.
}
@Override
public void initRequiredParams() {
this.requiredParams.add(OAuthConsts.OAuth.OAUTH_RESPONSE_TYPE);//REQUIRED. Value MUST be set to "code".
this.requiredParams.add(OAuthConsts.OAuth.OAUTH_CLIENT_ID);//REQUIRED. The client identifier as described in Section 2.2.
}
}
| 35.134615 | 124 | 0.773946 |
0cbfc586e947358c3b618942fcbba24f46dd3fa0 | 926 | package com.defano.hypertalk.ast.expressions.functions;
import com.defano.hypertalk.ast.expressions.Expression;
import com.defano.hypertalk.ast.model.Value;
import com.defano.hypertalk.exception.HtException;
import com.defano.wyldcard.WyldCard;
import com.defano.wyldcard.parts.stack.StackPart;
import com.defano.wyldcard.runtime.context.ExecutionContext;
import org.antlr.v4.runtime.ParserRuleContext;
import java.util.ArrayList;
public class StacksFunc extends Expression {
public StacksFunc(ParserRuleContext context) {
super(context);
}
@Override
protected Value onEvaluate(ExecutionContext context) throws HtException {
ArrayList<Value> stacks = new ArrayList<>();
for (StackPart thisStack : WyldCard.getInstance().getOpenStacks()) {
stacks.add(new Value(thisStack.getStackModel().getStackPath(context)));
}
return Value.ofLines(stacks);
}
}
| 30.866667 | 83 | 0.75054 |
af4bba989ce32687756adaca5140f01c5a33dc7e | 992 | package com.olacabs.jackhammer.models;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.io.Serializable;
import java.sql.Timestamp;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@JsonInclude(value=Include.NON_NULL)
public class AbstractModel implements Serializable {
protected long id;
protected String name;
protected Timestamp createdAt;
protected Timestamp updatedAt;
private String userToken;
//pagination fields
private long totalSize;
private long offset;
private long limit;
private long taskId;
private long ownerTypeId;
private long scanTypeId;
private String orderBy;
private String sortDirection;
private String searchTerm;
private Boolean createAllowed = false;
private Boolean readAllowed = false;
private Boolean updateAllowed = false;
private Boolean deleteAllowed = false;
private User user;
}
| 23.619048 | 60 | 0.758065 |
d27f8b8769550eb1e606080ef6a05c783b53195d | 733 | package com.naosim.someapp.infra.api.lib;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
public final class AnyTryCatcher {
private final List<Exception> exceptionList = new ArrayList<>();
public void run(Runnable r) {
try {
r.run();
} catch (Exception e) {
exceptionList.add(e);
}
}
public <T> Optional<T> get(Supplier<T> getter) {
try {
return Optional.of(getter.get());
} catch (Exception e) {
exceptionList.add(e);
return Optional.empty();
}
}
public List<Exception> getExceptionList() {
return exceptionList;
}
}
| 23.645161 | 68 | 0.592087 |
b687c82f1756d44e1f491cd224a25755f6681025 | 3,750 | /*
* 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 de.quadrillenschule.azocamsyncd.astromode_old;
import de.quadrillenschule.azocamsyncd.GlobalProperties;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.LinkedList;
/**
*
* @author Andreas
*/
public class ReceivePhotoSerie {
/**
* @return the exposureTimeInMs
*/
public long getExposureTimeInMs() {
return exposureTimeInMs;
}
/**
* @param exposureTimeInMs the exposureTimeInMs to set
*/
public void setExposureTimeInMs(long exposureTimeInMs) {
this.exposureTimeInMs = exposureTimeInMs;
}
/**
* @param project the project to set
*/
public void setProject(PhotoProject project) {
this.project = project;
}
public enum ReceiveStatus {
NEW, RECEIVING_FILES, COMPLETED
};
private ReceiveStatus status = ReceiveStatus.NEW;
private int numberOfPlannedPhotos = 0;
private String name = "lightframes";
private LinkedList<File> photos;
private PhotoProject project;
private long exposureTimeInMs=0;
public ReceivePhotoSerie(PhotoProject project) {
photos = new LinkedList<>();
this.project = project;
}
public void receiveFile(File file) throws IOException {
if (!project.getFolder().exists()) {
getProject().getFolder().mkdir();
}
if (!getFolder().exists()) {
getFolder().mkdir();
}
File newFile = new File(getFolder().getAbsolutePath(), file.getName());
Files.move(file.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
GlobalProperties gp = new GlobalProperties();
if (newFile.getAbsolutePath().toUpperCase().endsWith("JPG")) {
gp.setProperty(GlobalProperties.CamSyncProperties.LATESTIMAGEPATH, newFile.getAbsolutePath());
}
photos.add(file);
status = ReceiveStatus.RECEIVING_FILES;
if (isComplete()) {
status = ReceiveStatus.COMPLETED;
}
}
public boolean isComplete() {
return numberOfPlannedPhotos == photos.size();
}
/**
* @return the numberOfPhotos
*/
public int getNumberOfPlannedPhotos() {
return numberOfPlannedPhotos;
}
/**
* @param numberOfPlannedPhotos the numberOfPhotos to set
*/
public void setNumberOfPlannedPhotos(int numberOfPlannedPhotos) {
this.numberOfPlannedPhotos = numberOfPlannedPhotos;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the photos
*/
public LinkedList<File> getPhotos() {
return photos;
}
/**
* @return the status
*/
public ReceiveStatus getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(ReceiveStatus status) {
this.status = status;
}
/**
* @return the folder
*/
public File getFolder() {
File retval = new File(getProject().getFolder().getAbsolutePath(), getName());
return retval;
}
/**
* @return the project
*/
public PhotoProject getProject() {
return project;
}
}
| 25 | 107 | 0.598667 |
feb79f23d80b3f3345119244066a23fae9cc2d40 | 615 | // naive solution
public class Solution {
public String convert(String s, int nRows) {
StringBuffer[] sbs = new StringBuffer[nRows];
for (int i = 0; i < nRows; i++)
sbs[i] = new StringBuffer();
int i = 0, n = s.length();
while (i < n) {
for (int j = 0; j < nRows && i < n; j++, i++)
sbs[j].append(s.charAt(i));
for (int j = nRows - 2; j > 0 && i < n; j--, i++)
sbs[j].append(s.charAt(i));
}
for (i = 1; i < nRows; i++)
sbs[0].append(sbs[i]);
return sbs[0].toString();
}
} | 34.166667 | 61 | 0.442276 |
626ac84394d801374cd299fc3707f71a528918de | 125 | package com.thedeanda.ajaxproxy.ui.util;
public interface Reorderable {
public void reorder(int fromIndex, int toIndex);
}
| 20.833333 | 49 | 0.792 |
00cc8e035e9ef37b2129b6f6d882f96f422977bf | 23,323 | /**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.resources.commerce.catalog.admin;
import com.mozu.api.ApiContext;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import org.joda.time.DateTime;
import com.mozu.api.AsyncCallback;
import java.util.concurrent.CountDownLatch;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;
import com.mozu.api.DataViewMode;
/** <summary>
* Use the Product Reservations resource to temporarily hold a product from inventory while a shopper is filling out payment information. You can create a product reservation when a shopper proceeds to check out and then release the reservation when the order process is complete.
* </summary>
*/
public class ProductReservationResource {
///
/// <see cref="Mozu.Api.ApiContext"/>
///
private ApiContext _apiContext;
private DataViewMode _dataViewMode;
public ProductReservationResource(ApiContext apiContext)
{
_apiContext = apiContext;
_dataViewMode = DataViewMode.Live;
}
public ProductReservationResource(ApiContext apiContext, DataViewMode dataViewMode)
{
_apiContext = apiContext;
_dataViewMode = dataViewMode;
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* ProductReservationCollection productReservationCollection = productreservation.getProductReservations();
* </code></pre></p>
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.productadmin.ProductReservationCollection
* @see com.mozu.api.contracts.productadmin.ProductReservationCollection
*/
public com.mozu.api.contracts.productadmin.ProductReservationCollection getProductReservations() throws Exception
{
return getProductReservations( null, null, null, null, null);
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* CountDownLatch latch = productreservation.getProductReservations( callback );
* latch.await() * </code></pre></p>
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.productadmin.ProductReservationCollection
* @see com.mozu.api.contracts.productadmin.ProductReservationCollection
*/
public CountDownLatch getProductReservationsAsync( AsyncCallback<com.mozu.api.contracts.productadmin.ProductReservationCollection> callback) throws Exception
{
return getProductReservationsAsync( null, null, null, null, null, callback);
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* ProductReservationCollection productReservationCollection = productreservation.getProductReservations( startIndex, pageSize, sortBy, filter, responseFields);
* </code></pre></p>
* @param filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters.
* @param pageSize When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with this parameter set to 25, to get the 51st through the 75th items, set startIndex to 50.
* @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param sortBy The element to sort the results by and the channel in which the results appear. Either ascending (a-z) or descending (z-a) channel. Optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for more information.
* @param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with pageSize set to 25, to get the 51st through the 75th items, set this parameter to 50.
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.productadmin.ProductReservationCollection
* @see com.mozu.api.contracts.productadmin.ProductReservationCollection
*/
public com.mozu.api.contracts.productadmin.ProductReservationCollection getProductReservations(Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields) throws Exception
{
MozuClient<com.mozu.api.contracts.productadmin.ProductReservationCollection> client = com.mozu.api.clients.commerce.catalog.admin.ProductReservationClient.getProductReservationsClient(_dataViewMode, startIndex, pageSize, sortBy, filter, responseFields);
client.setContext(_apiContext);
client.executeRequest();
return client.getResult();
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* CountDownLatch latch = productreservation.getProductReservations( startIndex, pageSize, sortBy, filter, responseFields, callback );
* latch.await() * </code></pre></p>
* @param filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters.
* @param pageSize When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with this parameter set to 25, to get the 51st through the 75th items, set startIndex to 50.
* @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param sortBy The element to sort the results by and the channel in which the results appear. Either ascending (a-z) or descending (z-a) channel. Optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for more information.
* @param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with pageSize set to 25, to get the 51st through the 75th items, set this parameter to 50.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.productadmin.ProductReservationCollection
* @see com.mozu.api.contracts.productadmin.ProductReservationCollection
*/
public CountDownLatch getProductReservationsAsync(Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields, AsyncCallback<com.mozu.api.contracts.productadmin.ProductReservationCollection> callback) throws Exception
{
MozuClient<com.mozu.api.contracts.productadmin.ProductReservationCollection> client = com.mozu.api.clients.commerce.catalog.admin.ProductReservationClient.getProductReservationsClient(_dataViewMode, startIndex, pageSize, sortBy, filter, responseFields);
client.setContext(_apiContext);
return client.executeRequest(callback);
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* ProductReservation productReservation = productreservation.getProductReservation( productReservationId);
* </code></pre></p>
* @param productReservationId Unique identifier of the product reservation.
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.productadmin.ProductReservation
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public com.mozu.api.contracts.productadmin.ProductReservation getProductReservation(Integer productReservationId) throws Exception
{
return getProductReservation( productReservationId, null);
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* CountDownLatch latch = productreservation.getProductReservation( productReservationId, callback );
* latch.await() * </code></pre></p>
* @param productReservationId Unique identifier of the product reservation.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.productadmin.ProductReservation
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public CountDownLatch getProductReservationAsync(Integer productReservationId, AsyncCallback<com.mozu.api.contracts.productadmin.ProductReservation> callback) throws Exception
{
return getProductReservationAsync( productReservationId, null, callback);
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* ProductReservation productReservation = productreservation.getProductReservation( productReservationId, responseFields);
* </code></pre></p>
* @param productReservationId Unique identifier of the product reservation.
* @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.productadmin.ProductReservation
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public com.mozu.api.contracts.productadmin.ProductReservation getProductReservation(Integer productReservationId, String responseFields) throws Exception
{
MozuClient<com.mozu.api.contracts.productadmin.ProductReservation> client = com.mozu.api.clients.commerce.catalog.admin.ProductReservationClient.getProductReservationClient(_dataViewMode, productReservationId, responseFields);
client.setContext(_apiContext);
client.executeRequest();
return client.getResult();
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* CountDownLatch latch = productreservation.getProductReservation( productReservationId, responseFields, callback );
* latch.await() * </code></pre></p>
* @param productReservationId Unique identifier of the product reservation.
* @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @return com.mozu.api.contracts.productadmin.ProductReservation
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public CountDownLatch getProductReservationAsync(Integer productReservationId, String responseFields, AsyncCallback<com.mozu.api.contracts.productadmin.ProductReservation> callback) throws Exception
{
MozuClient<com.mozu.api.contracts.productadmin.ProductReservation> client = com.mozu.api.clients.commerce.catalog.admin.ProductReservationClient.getProductReservationClient(_dataViewMode, productReservationId, responseFields);
client.setContext(_apiContext);
return client.executeRequest(callback);
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* ProductReservation productReservation = productreservation.addProductReservations( productReservations);
* </code></pre></p>
* @param dataViewMode DataViewMode
* @param productReservations A hold placed on product inventory for a particular product so that the quantity specified is set aside and available for purchase during the ordering process.
* @return List<com.mozu.api.contracts.productadmin.ProductReservation>
* @see com.mozu.api.contracts.productadmin.ProductReservation
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public List<com.mozu.api.contracts.productadmin.ProductReservation> addProductReservations(List<com.mozu.api.contracts.productadmin.ProductReservation> productReservations) throws Exception
{
return addProductReservations( productReservations, null);
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* CountDownLatch latch = productreservation.addProductReservations( productReservations, callback );
* latch.await() * </code></pre></p>
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @param productReservations A hold placed on product inventory for a particular product so that the quantity specified is set aside and available for purchase during the ordering process.
* @return List<com.mozu.api.contracts.productadmin.ProductReservation>
* @see com.mozu.api.contracts.productadmin.ProductReservation
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public CountDownLatch addProductReservationsAsync(List<com.mozu.api.contracts.productadmin.ProductReservation> productReservations, AsyncCallback<List<com.mozu.api.contracts.productadmin.ProductReservation>> callback) throws Exception
{
return addProductReservationsAsync( productReservations, null, callback);
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* ProductReservation productReservation = productreservation.addProductReservations( productReservations, skipInventoryCheck);
* </code></pre></p>
* @param skipInventoryCheck If true, skip the process to validate inventory when creating this product reservation.
* @param dataViewMode DataViewMode
* @param productReservations A hold placed on product inventory for a particular product so that the quantity specified is set aside and available for purchase during the ordering process.
* @return List<com.mozu.api.contracts.productadmin.ProductReservation>
* @see com.mozu.api.contracts.productadmin.ProductReservation
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public List<com.mozu.api.contracts.productadmin.ProductReservation> addProductReservations(List<com.mozu.api.contracts.productadmin.ProductReservation> productReservations, Boolean skipInventoryCheck) throws Exception
{
MozuClient<List<com.mozu.api.contracts.productadmin.ProductReservation>> client = com.mozu.api.clients.commerce.catalog.admin.ProductReservationClient.addProductReservationsClient(_dataViewMode, productReservations, skipInventoryCheck);
client.setContext(_apiContext);
client.executeRequest();
return client.getResult();
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* CountDownLatch latch = productreservation.addProductReservations( productReservations, skipInventoryCheck, callback );
* latch.await() * </code></pre></p>
* @param skipInventoryCheck If true, skip the process to validate inventory when creating this product reservation.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @param productReservations A hold placed on product inventory for a particular product so that the quantity specified is set aside and available for purchase during the ordering process.
* @return List<com.mozu.api.contracts.productadmin.ProductReservation>
* @see com.mozu.api.contracts.productadmin.ProductReservation
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public CountDownLatch addProductReservationsAsync(List<com.mozu.api.contracts.productadmin.ProductReservation> productReservations, Boolean skipInventoryCheck, AsyncCallback<List<com.mozu.api.contracts.productadmin.ProductReservation>> callback) throws Exception
{
MozuClient<List<com.mozu.api.contracts.productadmin.ProductReservation>> client = com.mozu.api.clients.commerce.catalog.admin.ProductReservationClient.addProductReservationsClient(_dataViewMode, productReservations, skipInventoryCheck);
client.setContext(_apiContext);
return client.executeRequest(callback);
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* productreservation.commitReservations( productReservations);
* </code></pre></p>
* @param dataViewMode DataViewMode
* @param productReservations A hold placed on product inventory for a particular product so that the quantity specified is set aside and available for purchase during the ordering process.
* @return
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public void commitReservations(List<com.mozu.api.contracts.productadmin.ProductReservation> productReservations) throws Exception
{
MozuClient client = com.mozu.api.clients.commerce.catalog.admin.ProductReservationClient.commitReservationsClient(_dataViewMode, productReservations);
client.setContext(_apiContext);
client.executeRequest();
client.cleanupHttpConnection();
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* ProductReservation productReservation = productreservation.updateProductReservations( productReservations);
* </code></pre></p>
* @param dataViewMode DataViewMode
* @param productReservations A hold placed on product inventory for a particular product so that the quantity specified is set aside and available for purchase during the ordering process.
* @return List<com.mozu.api.contracts.productadmin.ProductReservation>
* @see com.mozu.api.contracts.productadmin.ProductReservation
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public List<com.mozu.api.contracts.productadmin.ProductReservation> updateProductReservations(List<com.mozu.api.contracts.productadmin.ProductReservation> productReservations) throws Exception
{
return updateProductReservations( productReservations, null);
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* CountDownLatch latch = productreservation.updateProductReservations( productReservations, callback );
* latch.await() * </code></pre></p>
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @param productReservations A hold placed on product inventory for a particular product so that the quantity specified is set aside and available for purchase during the ordering process.
* @return List<com.mozu.api.contracts.productadmin.ProductReservation>
* @see com.mozu.api.contracts.productadmin.ProductReservation
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public CountDownLatch updateProductReservationsAsync(List<com.mozu.api.contracts.productadmin.ProductReservation> productReservations, AsyncCallback<List<com.mozu.api.contracts.productadmin.ProductReservation>> callback) throws Exception
{
return updateProductReservationsAsync( productReservations, null, callback);
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* ProductReservation productReservation = productreservation.updateProductReservations( productReservations, skipInventoryCheck);
* </code></pre></p>
* @param skipInventoryCheck If true, skip the process to validate inventory when creating this product reservation.
* @param dataViewMode DataViewMode
* @param productReservations A hold placed on product inventory for a particular product so that the quantity specified is set aside and available for purchase during the ordering process.
* @return List<com.mozu.api.contracts.productadmin.ProductReservation>
* @see com.mozu.api.contracts.productadmin.ProductReservation
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public List<com.mozu.api.contracts.productadmin.ProductReservation> updateProductReservations(List<com.mozu.api.contracts.productadmin.ProductReservation> productReservations, Boolean skipInventoryCheck) throws Exception
{
MozuClient<List<com.mozu.api.contracts.productadmin.ProductReservation>> client = com.mozu.api.clients.commerce.catalog.admin.ProductReservationClient.updateProductReservationsClient(_dataViewMode, productReservations, skipInventoryCheck);
client.setContext(_apiContext);
client.executeRequest();
return client.getResult();
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* CountDownLatch latch = productreservation.updateProductReservations( productReservations, skipInventoryCheck, callback );
* latch.await() * </code></pre></p>
* @param skipInventoryCheck If true, skip the process to validate inventory when creating this product reservation.
* @param callback callback handler for asynchronous operations
* @param dataViewMode DataViewMode
* @param productReservations A hold placed on product inventory for a particular product so that the quantity specified is set aside and available for purchase during the ordering process.
* @return List<com.mozu.api.contracts.productadmin.ProductReservation>
* @see com.mozu.api.contracts.productadmin.ProductReservation
* @see com.mozu.api.contracts.productadmin.ProductReservation
*/
public CountDownLatch updateProductReservationsAsync(List<com.mozu.api.contracts.productadmin.ProductReservation> productReservations, Boolean skipInventoryCheck, AsyncCallback<List<com.mozu.api.contracts.productadmin.ProductReservation>> callback) throws Exception
{
MozuClient<List<com.mozu.api.contracts.productadmin.ProductReservation>> client = com.mozu.api.clients.commerce.catalog.admin.ProductReservationClient.updateProductReservationsClient(_dataViewMode, productReservations, skipInventoryCheck);
client.setContext(_apiContext);
return client.executeRequest(callback);
}
/**
*
* <p><pre><code>
* ProductReservation productreservation = new ProductReservation();
* productreservation.deleteProductReservation( productReservationId);
* </code></pre></p>
* @param productReservationId Unique identifier of the product reservation.
* @param dataViewMode DataViewMode
* @return
*/
public void deleteProductReservation(Integer productReservationId) throws Exception
{
MozuClient client = com.mozu.api.clients.commerce.catalog.admin.ProductReservationClient.deleteProductReservationClient(_dataViewMode, productReservationId);
client.setContext(_apiContext);
client.executeRequest();
client.cleanupHttpConnection();
}
}
| 58.017413 | 281 | 0.780517 |
6053c5063cc1d7df856d6865ae4c07c7615620d2 | 3,004 | package com.github.mybatis;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.github.mybatis.entity.BasisInfo;
import com.github.mybatis.util.EntityInfoUtil;
import com.github.mybatis.util.Generator;
import com.github.mybatis.util.MySqlToJavaUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TestMain {
//基础信息
public static final String PROJECT="qixingbao-show";
public static final String AUTHOR="hwh";
public static final String VERSION="V1.0";
//数据库连接信息
public static final String URL="jdbc:mysql://127.0.0.1:3306/mysql?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&useSSL=true";
public static final String NAME="root";
public static final String PASSWORD="123456";
public static final String DATABASE="mysql";
//类信息 如果多个以逗号分隔
public static final String TABLE="tb_log,plugin";
public static final String CLASSCOMMENT="用户,plugin";
public static final String TIME=new SimpleDateFormat("yyyy年MM月dd日").format(System.currentTimeMillis());
public static final String AGILE=System.currentTimeMillis()+"";
//路径信息
public static final String baseUrl = "com.qixingbao.show";
public static final String ENTITY_URL=baseUrl+".entity";
public static final String DAO_URL=baseUrl+".dao";
public static final String XML_URL=baseUrl+".dao.impl";
public static final String SERVICE_URL=baseUrl+".service";
public static final String SERVICE_IMPL_URL=baseUrl+".service.impl";
public static final String CONTROLLER_URL=baseUrl+".api";
public static void main(String[] args) {
String []tables = TABLE.split(",");
String []classComment = CLASSCOMMENT.split(",");
if(tables.length!=classComment.length){
System.out.println("表对应类的注释信息不匹配,请参考length:"+TABLE+"!="+CLASSCOMMENT+"");
System.exit(1);
}
int i=0;
for(String table:tables) {
BasisInfo bi = new BasisInfo(PROJECT, AUTHOR, VERSION, URL, NAME, PASSWORD, DATABASE, TIME, AGILE, ENTITY_URL, DAO_URL, XML_URL, SERVICE_URL, SERVICE_IMPL_URL, CONTROLLER_URL);
bi.setTable(table);
bi.setEntityName(MySqlToJavaUtil.getClassName(table));
bi.setObjectName(MySqlToJavaUtil.changeToJavaFiled(table));
bi.setEntityComment(classComment[i]);
try {
bi = EntityInfoUtil.getInfo(bi);
String projectPath = "/opt/" + PROJECT + "/src/main/java/";
String aa1 = Generator.createEntity(projectPath, bi).toString();
String aa2 = Generator.createDao(projectPath, bi).toString();
String aa3 = Generator.createDaoImpl(projectPath, bi).toString();
String aa4 = Generator.createService(projectPath, bi).toString();
String aa5 = Generator.createServiceImpl(projectPath, bi).toString();
String aa6 = Generator.createController(projectPath, bi).toString();
System.out.println(aa1);
System.out.println(aa2);
System.out.println(aa3);
System.out.println(aa4);
System.out.println(aa5);
System.out.println(aa6);
} catch (SQLException e) {
e.printStackTrace();
}
i++;
}
}
}
| 39.012987 | 179 | 0.747004 |
1a1b1f98f2d50f55ccaacdccb3f998cfb6d9f1f6 | 697 | package org.consensusj.bitcoin.proxy.jsonrpc;
import io.micronaut.http.HttpResponse;
import org.consensusj.jsonrpc.JsonRpcRequest;
import org.reactivestreams.Publisher;
/**
* Interface for proxying JSON-RPC requests using Reactive Streams {@link Publisher}
* and Micronaut {link @HttpResponse} types.
*/
public interface RxJsonRpcProxyService {
/**
*
* @param request A deserialized (for filtering) request
* @return A promise of a serialized response
*/
Publisher<HttpResponse<String>> rpcProxy(JsonRpcRequest request);
Publisher<HttpResponse<String>> rpcProxy(String method);
Publisher<HttpResponse<String>> rpcProxy(String method, String... args);
}
| 29.041667 | 84 | 0.747489 |
7a66246a4712cfc66d2fa553ba6c27f29fb47dd0 | 3,656 | /*---------------------------------------------------------------------
* Copyright (c) 2021 Veeva Systems Inc. All Rights Reserved.
* This code is based on pre-existing content developed and
* owned by Veeva Systems Inc. and may only be used in connection
* with the deliverable with which it was provided to Customer.
*---------------------------------------------------------------------
*/
package com.veeva.vault.vapil.api.request;
import com.veeva.vault.vapil.api.client.VaultClient;
import com.veeva.vault.vapil.api.model.metadata.Group;
import com.veeva.vault.vapil.api.model.response.GroupResponse;
import com.veeva.vault.vapil.api.model.response.GroupRetrieveResponse;
import com.veeva.vault.vapil.api.model.response.MetaDataGroupResponse;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import com.veeva.vault.vapil.extension.VaultClientParameterResolver;
import java.util.List;
import java.util.Random;
@Tag("GroupRequest")
@ExtendWith(VaultClientParameterResolver.class)
public class GroupRequestTest {
@Test
public void testRetrieveGroupMetaData(VaultClient vaultClient) {
MetaDataGroupResponse response = vaultClient.newRequest(GroupRequest.class)
.retrieveGroupMetadata();
Assertions.assertTrue(response.isSuccessful());
List<Group> allGroupMetaData = response.getProperties();
Assertions.assertNotNull(allGroupMetaData);
Assertions.assertFalse(allGroupMetaData.isEmpty());
}
@Test
public void testRetrieveAllGroups(VaultClient vaultClient) {
GroupRetrieveResponse response = vaultClient.newRequest(GroupRequest.class)
.setIncludeImplied(true)
.retrieveAllGroups(true);
Assertions.assertTrue(response.isSuccessful());
}
@Test
public void testRetrieveGroup(VaultClient vaultClient) {
GroupRetrieveResponse response = vaultClient.newRequest(GroupRequest.class)
.setIncludeImplied(true)
.retrieveGroup(1); // All Internal Users
Assertions.assertTrue(response.isSuccessful());
}
@Test
public void testCreateGroup(VaultClient vaultClient) {
String label = "testGroup" + getRandomNumberAsString(1, 100, 3);
GroupResponse response = vaultClient.newRequest(GroupRequest.class)
.createGroup(label);
Assertions.assertTrue(response.isSuccessful());
Assertions.assertNotNull(response.getId());
}
@Nested
@DisplayName("Tests that depend on an existing group")
class TestGroupUpdateAndDelete {
Long groupId;
@BeforeEach
public void beforeEach(VaultClient vaultClient){
String label = "testGroup" + getRandomNumberAsString(1, 100, 3);
GroupResponse response = vaultClient.newRequest(GroupRequest.class)
.createGroup(label);
Assertions.assertTrue(response.isSuccessful());
groupId = response.getId();
}
@Test
public void testUpdateGroup(VaultClient vaultClient) {
GroupResponse response = vaultClient.newRequest(GroupRequest.class)
.setLabel("testGroup" + groupId)
.setActive(false)
.setGroupDescription("Description " + groupId)
.setAllowDelegationAmongMembers(true)
.updateGroup(groupId);
Assertions.assertTrue(response.isSuccessful());
Assertions.assertNotNull(response.getId());
}
@Test
public void testDeleteGroup(VaultClient vaultClient) {
GroupResponse response = vaultClient.newRequest(GroupRequest.class).deleteGroup(groupId);
Assertions.assertTrue(response.isSuccessful());
Assertions.assertNotNull(response.getId());
}
}
public String getRandomNumberAsString(int min, int max, int paddedNumLength) {
Random rnd = new Random();
int rndInt = rnd.nextInt((max - min) + 1) + min;
return String.format("%0" + paddedNumLength + "d", rndInt);
}
}
| 35.153846 | 92 | 0.74453 |
e5607512fcff75789f4c3a24362177c4b39847b4 | 659 | class Solution {
public List<List<Integer>> XXX(int[] nums) {
if(nums.length<3){
return new ArrayList();
}
List<Integer> temp=new ArrayList<>();
dfs(nums,temp,0);
return res;
}
public List<List<Integer>> res=new ArrayList<>();
public void dfs(int [] nums,List<Integer> temp,int len){
if(temp.size()==3&&temp.get(0)+temp.get(1)+temp.get(2)==0){
res.add(new ArrayList(temp));
return;
}
for(int i=len;i<nums.length;i++){
temp.add(nums[i]);
dfs(nums,temp,i+1);
temp.remove(temp.size()-1);
}
}
}
| 25.346154 | 67 | 0.500759 |
ef248f6595ed465dbda4bb378c3fab0c97d6b99b | 372 | package com.zbiljic.failure;
import com.zbiljic.failure.http.HttpStatus;
/**
* @author Nemanja Zbiljic
*/
final class GenericFailures {
static FailureBuilder create(final String service, final HttpStatus status) {
return Failure.builder(service)
.withTitle(status.getReasonPhrase())
.withStatus(status)
.withCode(status.value());
}
}
| 20.666667 | 79 | 0.706989 |
ccb00d96261524b83a421f487046b1d4abbf9b2d | 18,672 | package me.gopro336.zenith.feature.toggleable.render;
import me.gopro336.zenith.feature.AnnotationHelper;
import me.gopro336.zenith.feature.Category;
import me.gopro336.zenith.feature.Feature;
import me.gopro336.zenith.property.NumberProperty;
import me.gopro336.zenith.property.Property;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.monster.EntityIronGolem;
import net.minecraft.entity.passive.EntityAmbientCreature;
import net.minecraft.entity.passive.EntitySquid;
import net.minecraft.entity.passive.EntityTameable;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import java.awt.*;
/*gg*/
@AnnotationHelper(name = "Chams", description = "", category = Category.RENDER)
public class NewChams extends Feature {
public static NewChams INSTANCE = new NewChams();
public static Property<Boolean> Field2096;
//public static Property<Class524> Field2097;
public static Property<Boolean> Field2098;
public static Property<Boolean> Field2099;
public static Property<Class495> Field2100;
public static Property<Boolean> Field2101;
public static NumberProperty<Float> Field2102;
public static NumberProperty<Float> Field2103;
public static Property<Color> Field2104;
public static Property<Boolean> Field2105;
public static Property<Boolean> Field2106;
public static Property<Boolean> Field2107;
public static Property<Color> Field2108;
public static Property<Boolean> Field2109;
public static Property<Boolean> Field2110;
public static NumberProperty<Float> Field2111;
public static Property<Color> Field2112;
public static Property<Boolean> Field2113;
public static Property<Boolean> Field2114;
public static Property<Boolean> Field2115;
public static Property<Boolean> Field2116;
public static Property<Boolean> Field2117;
public static Property<Boolean> Field2118;
public static Property<Boolean> Field2119;
public static Property<Boolean> Field2120;
public static Property<Boolean> Field2121;
public static Property<Class495> Field2122;
public static Property<Boolean> Field2123;
public static NumberProperty<Float> Field2124;
public static NumberProperty<Float> Field2125;
public static Property<Color> Field2126;
public static Property<Boolean> Field2127;
public static Property<Boolean> Field2128;
public static Property<Boolean> Field2129;
public static Property<Color> Field2130;
public static Property<Boolean> Field2131;
public static Property<Boolean> Field2132;
public static NumberProperty<Float> Field2133;
public static Property<Color> Field2134;
public static NumberProperty<Float> Field2135;
public static NumberProperty<Float> Field2136;
public static NumberProperty<Float> Field2137;
public static Property<Boolean> Field2138;
public static Property<Boolean> Field2139;
public static Property<Color> Field2140;
public static Property<Class495> Field2141;
public static NumberProperty<Float> Field2142;
public static NumberProperty<Float> Field2143;
public static Property<Color> Field2144;
public NewChams(){
Field2096 = new Property<>(this, "Living", "", false);
//public static Property<Class524> Field2097 = new Property<>(this, "Preview", new Class524(false, true)).setParentProperty(Field2096);
Field2098 = new Property<>(this, Field2096, "Render", "", false);
Field2099 = new Property<>(this, Field2096, "RenderDepth", "", false);
Field2100 = new Property<>(this, Field2096, "Glint", "", Class495.NONE);
Field2101 = new Property<>(this, Field2096, "GlintDepth", "", false);
Field2102 = new NumberProperty<>(this, Field2096, "GlintSpeed ", "", 0.1f, 5.0f, 20.0f);
Field2103 = new NumberProperty<>(this, Field2096, "GlintScale ", "", 0.1f, 1.0f, 10.0f);
Field2104 = new Property<>(this, Field2096, "GlintColor", "", new Color(0x7700FFFF));
Field2105 = new Property<>(this, Field2096, "Fill", "", false);
Field2106 = new Property<>(this, Field2096, "FillDepth", "", false);
Field2107 = new Property<>(this, Field2096, "Lighting", "", false);
Field2108 = new Property<>(this, Field2096, "FillColor", "", new Color(0x7700FFFF));
Field2109 = new Property<>(this, Field2096, "Outline", "", false);
Field2110 = new Property<>(this, Field2096, "OutlineDepth", "", false);
Field2111 = new NumberProperty<>(this, Field2096, "Width ", "", 0.1f, 1.0f, 10.0f);
Field2112 = new Property<>(this, Field2096, "GOutlineColor", "", new Color(-16711681));
Field2113 = new Property<>(this, Field2096, "Players", "", true);
Field2114 = new Property<>(this, Field2096, "Self", "", true);
Field2115 = new Property<>(this, Field2096, "Animals", "", true);
Field2116 = new Property<>(this, Field2096, "Monsters", "", true);
Field2117 = new Property<>(this, Field2096, "Invis", "", true);
Field2118 = new Property<>(this, "Crystal", "", false);
Field2119 = new Property<>(this, Field2118, "Crystals", "", true);
Field2120 = new Property<>(this, Field2118, "CRender", "", false);
Field2121 = new Property<>(this, Field2118, "CRenderDepth", "", false);
Field2122 = new Property<>(this, Field2118, "CGlint", "", Class495.NONE);
Field2123 = new Property<>(this, Field2118, "CGlintDepth", "", false);
Field2124 = new NumberProperty<>(this, Field2118, "CGlintSpeed ", "", 0.1f, 5.0f, 20.0f);
Field2125 = new NumberProperty<>(this, Field2118, "CGlintScale ", "", 0.1f, 1.0f, 10.0f);
Field2126 = new Property<>(this, Field2118, "CGlintColor", "", new Color(0x770000FF));
Field2127 = new Property<>(this, Field2118, "CFill", "", false);
Field2128 = new Property<>(this, Field2118, "CFillDepth", "", false);
Field2129 = new Property<>(this, Field2118, "CLighting", "", false);
Field2130 = new Property<>(this, Field2118, "CFillColor", "", new Color(0x770000FF));
Field2131 = new Property<>(this, Field2118, "COutline", "", false);
Field2132 = new Property<>(this, Field2118, "COutlineDepth", "", false);
Field2133 = new NumberProperty<>(this, Field2118, "CWidth ", "", 0.1f, 1.0f, 10.0f);
Field2134 = new Property<>(this, Field2118, "CGOutlineColor", "", new Color(-16776961));
Field2135 = new NumberProperty<>(this, Field2118, "Scale ", "", 0.1f, 1.0f, 10.0f);
Field2136 = new NumberProperty<>(this, Field2118, "SpinSpeed ", "", 0.1f, 1.0f, 10.0f);
Field2137 = new NumberProperty<>(this, Field2118, "Bounciness ", "", 0.1f, 1.0f, 10.0f);
Field2138 = new Property<>(this, "Hand", "", false);
Field2139 = new Property<>(this, Field2138, "Hands", "", true);
Field2140 = new Property<>(this, Field2138, "HandColor", "", new Color(469762303));
Field2141 = new Property<>(this, Field2138, "HGlint", "", Class495.NONE);
Field2142 = new NumberProperty<>(this, Field2138, "HGlintSpeed ", "", 0.1f, 5.0f, 20.0f);
Field2143 = new NumberProperty<>(this, Field2138, "HGlintScale ", "", 0.1f, 1.0f, 10.0f);
Field2144 = new Property<>(this, Field2138, "HGlintColor", "", new Color(0x770000FF));
setInstance();
}
public static NewChams getInstance() {
if (INSTANCE == null) {
INSTANCE = new NewChams();
}
return INSTANCE;
}
private void setInstance() {
INSTANCE = this;
}
public enum Class495{
NONE,
VANILLA,
CUSTOM
}
public static ResourceLocation Field2145 = new ResourceLocation("textures/misc/enchanted_item_glint.png");
public static ResourceLocation Field2146 = new ResourceLocation("konas/textures/enchant_glint.png");
public static boolean Field2147 = false;
public static boolean Method513(Entity entity) {
if (entity == null) {
return false;
}
if (entity.isInvisible() && !((Boolean)Field2117.getValue()).booleanValue()) {
return false;
}
if (entity.equals((Object)mc.player) && !((Boolean)Field2114.getValue()).booleanValue()) {
return false;
}
if (entity instanceof EntityPlayer && !((Boolean)Field2113.getValue()).booleanValue()) {
return false;
}
if (Method386(entity) && !((Boolean)Field2115.getValue()).booleanValue()) {
return false;
}
return Method386(entity) || entity instanceof EntityPlayer || (Boolean)Field2116.getValue() != false;
}
public static void Method1948(Color class440, ModelBase modelBase, Entity entity, float f, float f2, float f3, float f4, float f5, float f6, float f7) {
GL11.glPushMatrix();
GL11.glPushAttrib((int)1048575);
GL11.glPolygonMode((int)1032, (int)6914);
GL11.glDisable((int)2896);
GL11.glDisable((int)2929);
GL11.glEnable((int)3042);
Minecraft.getMinecraft().getRenderManager().renderEngine.bindTexture(Field2100.getValue() == Class495.CUSTOM ? Field2146 : Field2145);
GL11.glPolygonMode((int)1032, (int)6914);
GL11.glDisable((int)2896);
GL11.glDisable((int)2929);
GL11.glEnable((int)3042);
//GL11.glColor4f((float)((float)class440.getRed() / 255.0f), (float)((float)class440.getGreen() / 255.0f), (float)((float)class440.getBlue() / 255.0f), (float)((float)class440.getAlpha() / 255.0f));
GL11.glColor4f((float)((float)Method769(class440.getRGB()) / 255.0f), (float)((float)Method770(class440.getRGB()) / 255.0f), (float)((float)Method779(class440.getRGB()) / 255.0f), (float)((float)Method782(class440.getRGB()) / 255.0f));
GlStateManager.blendFunc((GlStateManager.SourceFactor)GlStateManager.SourceFactor.SRC_COLOR, (GlStateManager.DestFactor)GlStateManager.DestFactor.ONE);
for (int i = 0; i < 2; ++i) {
GlStateManager.matrixMode((int)5890);
GlStateManager.loadIdentity();
float f8 = 0.33333334f * ((Float)Field2103.getValue()).floatValue();
GlStateManager.scale((float)f8, (float)f8, (float)f8);
GlStateManager.rotate((float)(30.0f - (float)i * 60.0f), (float)0.0f, (float)0.0f, (float)1.0f);
GlStateManager.translate((float)0.0f, (float)(((float)entity.ticksExisted + mc.getRenderPartialTicks()) * (0.001f + (float)i * 0.003f) * ((Float)Field2102.getValue()).floatValue()), (float)0.0f);
GlStateManager.matrixMode((int)5888);
GL11.glTranslatef((float)f7, (float)f7, (float)f7);
//GlStateManager.color((float)((float)class440.getRed() / 255.0f), (float)((float)class440.getGreen() / 255.0f), (float)((float)class440.getBlue() / 255.0f), (float)((float)class440.getAlpha() / 255.0f));
GlStateManager.color((float)((float)Method769(class440.getRGB()) / 255.0f), (float)((float)Method770(class440.getRGB()) / 255.0f), (float)((float)Method779(class440.getRGB()) / 255.0f), (float)((float)Method782(class440.getRGB()) / 255.0f));
if (((Boolean)Field2101.getValue()).booleanValue()) {
GL11.glDepthMask((boolean)true);
GL11.glEnable((int)2929);
}
modelBase.render(entity, f, f2, f3, f4, f5, f6);
if (!((Boolean)Field2101.getValue()).booleanValue()) continue;
GL11.glDisable((int)2929);
GL11.glDepthMask((boolean)false);
}
GlStateManager.matrixMode((int)5890);
GlStateManager.loadIdentity();
GlStateManager.matrixMode((int)5888);
GlStateManager.blendFunc((GlStateManager.SourceFactor)GlStateManager.SourceFactor.ONE, (GlStateManager.DestFactor)GlStateManager.DestFactor.ZERO);
GlStateManager.color((float)1.0f, (float)1.0f, (float)1.0f, (float)1.0f);
GL11.glPopAttrib();
GL11.glPopMatrix();
}
/*@Listener
public void renderRightArm(RenderRightArmEvent class102) {
block0: {
if (!((Boolean)Field2139.getValue()).booleanValue()) break block0;
class102.Method341(((Color)Field2140.getValue()).Method769());
class102.Method344(((Color)Field2140.getValue()).Method770());
class102.Method1102(((Color)Field2140.getValue()).Method779());
class102.Method294(((Color)Field2140.getValue()).Method782());
class102.Method1236(true);
}
}*/
public static void Method1950(Color class440, ModelBase modelBase, Entity entity, float f, float f2, float f3, float f4, float f5, float f6, float f7) {
GL11.glPushMatrix();
GL11.glPushAttrib((int)1048575);
GL11.glPolygonMode((int)1032, (int)6914);
GL11.glDisable((int)3553);
if (((Boolean)Field2107.getValue()).booleanValue()) {
GL11.glEnable((int)2896);
} else {
GL11.glDisable((int)2896);
}
GL11.glDisable((int)2929);
GL11.glEnable((int)2848);
GL11.glEnable((int)3042);
GL11.glBlendFunc((int)770, (int)771);
GL11.glTranslatef((float)f7, (float)f7, (float)f7);
//GlStateManager.color((float)((float)class440.getRed() / 255.0f), (float)((float)class440.getGreen() / 255.0f), (float)((float)class440.getBlue() / 255.0f), (float)((float)class440.getAlpha() / 255.0f));
GlStateManager.color((float)((float)Method769(class440.getRGB()) / 255.0f), (float)((float)Method770(class440.getRGB()) / 255.0f), (float)((float)Method779(class440.getRGB()) / 255.0f), (float)((float)Method782(class440.getRGB()) / 255.0f));
if (((Boolean)Field2106.getValue()).booleanValue()) {
GL11.glDepthMask((boolean)true);
GL11.glEnable((int)2929);
}
modelBase.render(entity, f, f2, f3, f4, f5, f6);
if (((Boolean)Field2106.getValue()).booleanValue()) {
GL11.glDisable((int)2929);
GL11.glDepthMask((boolean)false);
}
GlStateManager.resetColor();
GL11.glPopAttrib();
GL11.glPopMatrix();
}
public static void Method1951(Color class440, float f, ModelBase modelBase, Entity entity, float f2, float f3, float f4, float f5, float f6, float f7, float f8) {
GL11.glPushMatrix();
GL11.glPushAttrib((int)1048575);
GL11.glPolygonMode((int)1032, (int)6913);
GL11.glDisable((int)3553);
GL11.glDisable((int)2896);
GL11.glDisable((int)2929);
GL11.glEnable((int)2848);
GL11.glEnable((int)3042);
GL11.glBlendFunc((int)770, (int)771);
GL11.glTranslatef((float)f8, (float)f8, (float)f8);
//GlStateManager.color((float)((float)class440.getRed() / 255.0f), (float)((float)class440.getGreen() / 255.0f), (float)((float)class440.getBlue() / 255.0f), (float)((float)class440.getAlpha() / 255.0f));
GlStateManager.color((float)((float)Method769(class440.getRGB()) / 255.0f), (float)((float)Method770(class440.getRGB()) / 255.0f), (float)((float)Method779(class440.getRGB()) / 255.0f), (float)((float)Method782(class440.getRGB()) / 255.0f));
GlStateManager.glLineWidth((float)f);
if (((Boolean)Field2110.getValue()).booleanValue()) {
GL11.glDepthMask((boolean)true);
GL11.glEnable((int)2929);
}
modelBase.render(entity, f2, f3, f4, f5, f6, f7);
if (((Boolean)Field2110.getValue()).booleanValue()) {
GL11.glDisable((int)2929);
GL11.glDepthMask((boolean)false);
}
GlStateManager.resetColor();
GL11.glPopAttrib();
GL11.glPopMatrix();
}
public static boolean renderEntityChams(ModelBase modelBase, Entity entity, float f, float f2, float f3, float f4, float f5, float f6) {
if (!Method513(entity)) {
return false;
}
boolean bl = mc.gameSettings.fancyGraphics;
mc.gameSettings.fancyGraphics = false;
if (((Boolean)Field2098.getValue()).booleanValue()) {
if (!((Boolean)Field2099.getValue()).booleanValue()) {
OpenGlHelper.setLightmapTextureCoords((int)OpenGlHelper.lightmapTexUnit, (float)240.0f, (float)240.0f);
GL11.glEnable((int)32823);
GL11.glPolygonOffset((float)1.0f, (float)-1100000.0f);
}
modelBase.render(entity, f, f2, f3, f4, f5, f6);
if (!((Boolean)Field2099.getValue()).booleanValue()) {
GL11.glDisable((int)32823);
GL11.glPolygonOffset((float)1.0f, (float)1100000.0f);
}
}
float f7 = mc.gameSettings.gammaSetting;
mc.gameSettings.gammaSetting = 10000.0f;
if (Field2105.getValue()) {
Method1950((Color)Field2108.getValue(), modelBase, entity, f, f2, f3, f4, f5, f6, 0.0f);
}
if (Field2109.getValue()) {
Method1951((Color)Field2112.getValue(), (Float) Field2111.getValue(), modelBase, entity, f, f2, f3, f4, f5, f6, 0.0f);
}
if (Field2100.getValue() != Class495.NONE) {
Method1948((Color)Field2104.getValue(), modelBase, entity, f, f2, f3, f4, f5, f6, 0.0f);
}
try {
mc.gameSettings.fancyGraphics = bl;
mc.gameSettings.gammaSetting = f7;
}
catch (Exception exception) {
// empty catch block
}
return true;
}
public static boolean Method386(Entity entity) {
if (entity instanceof EntityWolf) {
return !((EntityWolf)entity).isAngry();
}
if (entity instanceof EntityAgeable || entity instanceof EntityTameable || entity instanceof EntityAmbientCreature || entity instanceof EntitySquid) {
return true;
}
if (entity instanceof EntityIronGolem) {
return ((EntityIronGolem)entity).getRevengeTarget() == null;
}
return false;
}
public static int Method769(int Field725) {
return Field725 >> 16 & 0xFF;
}
public static int Method770(int Field725) {
return Field725 >> 8 & 0xFF;
}
public static int Method779(int Field725) {
return Field725 & 0xFF;
}
public static int Method782(int Field725) {
return Field725 >> 24 & 0xFF;
}
}
| 46.447761 | 253 | 0.644066 |
a400188ba51c1e791649781a92f77d830f7159ad | 217 | package org.javault;
/**
* Internal exception for feedback to the client code
*/
public class VaultRunException extends Exception {
public VaultRunException(String message, Throwable t){
super(message, t);
}
}
| 19.727273 | 55 | 0.751152 |
0676a187aa44849e4bcb2ee940672097acf017f1 | 821 | package cc.ntechnologies.service;
import cc.ntechnologies.dao.RoomDao;
import cc.ntechnologies.entities.Room;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.io.Serializable;
import java.util.List;
@Service
public class RoomService implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private RoomDao roomDao;
public void save(Room room) {
roomDao.save(room);
}
public void delete(Room room) {
roomDao.delete(room);
}
public Room findRoomById(Long id) {
return roomDao.findById(id);
}
public List<Room> getAll(int first, int pageSize) {
return roomDao.getAll(first, pageSize);
}
public int getNumberOfRooms() {
return roomDao.getNumberOfRooms();
}
}
| 21.051282 | 55 | 0.695493 |
1a1108b78833eee0d945608546bb8f0d8ce8b331 | 955 | package def;
public class Book {
public int id = 0;
public String title = "";
public String author = "";
public int year = 2020;
public int pages = 0;
public boolean borrow = false;
public int by = 0;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public boolean isBorrow() {
return borrow;
}
public void setBorrow(boolean borrow) {
this.borrow = borrow;
}
public int getBy() {
return by;
}
public void setBy(int by) {
this.by = by;
}
}
| 13.450704 | 40 | 0.633508 |
afd6428f1991ff9e04bc747530aebbc27ea64e9d | 4,457 | package au.edu.ardc.registry.igsn.validator;
import au.edu.ardc.registry.common.model.User;
import au.edu.ardc.registry.common.service.IdentifierService;
import au.edu.ardc.registry.common.service.SchemaService;
import au.edu.ardc.registry.common.service.ValidationService;
import au.edu.ardc.registry.common.service.VersionService;
import au.edu.ardc.registry.exception.*;
import au.edu.ardc.registry.igsn.validator.ContentValidator;
import au.edu.ardc.registry.igsn.validator.UserAccessValidator;
import au.edu.ardc.registry.igsn.validator.VersionContentValidator;
import java.io.IOException;
/**
* Payload Validator is the top level validator when records sent to the registry it
* performs several validations Content validation to check if xml or json or csv is well
* formed and valid User access validation checks if user has the desired access for the
* allocations needed to complete the tasks if Update content then also checks content if
* Record has a version with the given schema and it is different from the current one
*/
public class PayloadValidator {
private final ContentValidator contentValidator;
private final UserAccessValidator userAccessValidator;
private final VersionContentValidator versionContentValidator;
/**
* Constructor when the various validators are already defined elsewhere
* @param contentValidator {@link ContentValidator}
* @param versionContentValidator {@link VersionContentValidator}
* @param userAccessValidator {@link UserAccessValidator}
*/
public PayloadValidator(ContentValidator contentValidator, VersionContentValidator versionContentValidator,
UserAccessValidator userAccessValidator) {
this.contentValidator = contentValidator;
this.userAccessValidator = userAccessValidator;
this.versionContentValidator = versionContentValidator;
}
/**
* Constructor that builds it's own set of Validators. Since this is an instance and
* not a {@link org.springframework.stereotype.Service}. All Service object. needs to
* be passed in and can't be automatically injected.
* @param schemaService {@link SchemaService}
* @param validationService {@link ValidationService}
* @param identifierService {@link IdentifierService}
* @param versionService {@link VersionService}
*/
public PayloadValidator(SchemaService schemaService, ValidationService validationService,
IdentifierService identifierService, VersionService versionService) {
this.contentValidator = new ContentValidator(schemaService);
this.userAccessValidator = new UserAccessValidator(identifierService, validationService, schemaService);
this.versionContentValidator = new VersionContentValidator(identifierService, schemaService);
}
/**
* The {@link UserAccessValidator} holds a mutable state.
* @return The instance of {@link UserAccessValidator}
*/
public UserAccessValidator getUserAccessValidator() {
return this.userAccessValidator;
}
/**
* @param content String the payload content as String
* @param user the logged in User who requested the mint / update
* @throws IOException and other type of exceptions by contentValidator and user
* access validator
*/
public void validateMintPayload(String content, User user) throws IOException, ContentNotSupportedException,
XMLValidationException, JSONValidationException, ForbiddenOperationException {
// validate the entire XML or JSON content
contentValidator.validate(content);
// check if the current user has insert or update access for the records with the
// given identifiers
userAccessValidator.canUserCreateIGSNRecord(content, user);
}
/**
* @param content String the payload content as String
* @param user the logged in User who requested the mint / update
* @throws IOException and other type of exceptions by contentValidator and user
* access validator
*/
public void validateUpdatePayload(String content, User user)
throws IOException, ContentNotSupportedException, XMLValidationException, JSONValidationException,
ForbiddenOperationException, VersionContentAlreadyExistsException {
// validate the entire XML or JSON content
contentValidator.validate(content);
// check if the current user has insert or update access for the records with the
// given identifiers
userAccessValidator.canUserUpdateIGSNRecord(content, user);
// check if the contents are new compared what stored in the registry
versionContentValidator.isNewContent(content);
}
}
| 44.128713 | 109 | 0.801885 |
71e23a99b176999af9e6a0233d850299120ad8c4 | 5,676 | package org.apache.lucene.search;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.index.TermDocs; // for javadocs
/**
* A {@link Filter} that only accepts documents whose single
* term value in the specified field is contained in the
* provided set of allowed terms.
*
* <p/>
*
* This is the same functionality as TermsFilter (from
* contrib/queries), except this filter requires that the
* field contains only a single term for all documents.
* Because of drastically different implementations, they
* also have different performance characteristics, as
* described below.
*
* <p/>
*
* The first invocation of this filter on a given field will
* be slower, since a {@link FieldCache.StringIndex} must be
* created. Subsequent invocations using the same field
* will re-use this cache. However, as with all
* functionality based on {@link FieldCache}, persistent RAM
* is consumed to hold the cache, and is not freed until the
* {@link IndexReader} is closed. In contrast, TermsFilter
* has no persistent RAM consumption.
*
*
* <p/>
*
* With each search, this filter translates the specified
* set of Terms into a private {@link FixedBitSet} keyed by
* term number per unique {@link IndexReader} (normally one
* reader per segment). Then, during matching, the term
* number for each docID is retrieved from the cache and
* then checked for inclusion using the {@link FixedBitSet}.
* Since all testing is done using RAM resident data
* structures, performance should be very fast, most likely
* fast enough to not require further caching of the
* DocIdSet for each possible combination of terms.
* However, because docIDs are simply scanned linearly, an
* index with a great many small documents may find this
* linear scan too costly.
*
* <p/>
*
* In contrast, TermsFilter builds up an {@link FixedBitSet},
* keyed by docID, every time it's created, by enumerating
* through all matching docs using {@link TermDocs} to seek
* and scan through each term's docID list. While there is
* no linear scan of all docIDs, besides the allocation of
* the underlying array in the {@link FixedBitSet}, this
* approach requires a number of "disk seeks" in proportion
* to the number of terms, which can be exceptionally costly
* when there are cache misses in the OS's IO cache.
*
* <p/>
*
* Generally, this filter will be slower on the first
* invocation for a given field, but subsequent invocations,
* even if you change the allowed set of Terms, should be
* faster than TermsFilter, especially as the number of
* Terms being matched increases. If you are matching only
* a very small number of terms, and those terms in turn
* match a very small number of documents, TermsFilter may
* perform faster.
*
* <p/>
*
* Which filter is best is very application dependent.
*/
public class FieldCacheTermsFilter extends Filter {
private String field;
private String[] terms;
public FieldCacheTermsFilter(String field, String... terms) {
this.field = field;
this.terms = terms;
}
public FieldCache getFieldCache() {
return FieldCache.DEFAULT;
}
@Override
public DocIdSet getDocIdSet(IndexReader reader) throws IOException {
return new FieldCacheTermsFilterDocIdSet(getFieldCache().getStringIndex(reader, field));
}
protected class FieldCacheTermsFilterDocIdSet extends DocIdSet {
private FieldCache.StringIndex fcsi;
private FixedBitSet bits;
public FieldCacheTermsFilterDocIdSet(FieldCache.StringIndex fcsi) {
this.fcsi = fcsi;
bits = new FixedBitSet(this.fcsi.lookup.length);
for (int i=0;i<terms.length;i++) {
int termNumber = this.fcsi.binarySearchLookup(terms[i]);
if (termNumber > 0) {
bits.set(termNumber);
}
}
}
@Override
public DocIdSetIterator iterator() {
return new FieldCacheTermsFilterDocIdSetIterator();
}
/** This DocIdSet implementation is cacheable. */
@Override
public boolean isCacheable() {
return true;
}
protected class FieldCacheTermsFilterDocIdSetIterator extends DocIdSetIterator {
private int doc = -1;
@Override
public int docID() {
return doc;
}
@Override
public int nextDoc() {
try {
while (!bits.get(fcsi.order[++doc])) {}
} catch (ArrayIndexOutOfBoundsException e) {
doc = NO_MORE_DOCS;
}
return doc;
}
@Override
public int advance(int target) {
try {
doc = target;
while (!bits.get(fcsi.order[doc])) {
doc++;
}
} catch (ArrayIndexOutOfBoundsException e) {
doc = NO_MORE_DOCS;
}
return doc;
}
}
}
}
| 32.62069 | 92 | 0.700317 |
a1a15d6ff9b9ab352d0477006229ceffe16f8915 | 377 | package com.py.py.dto.in;
import com.py.py.dto.DTO;
public class SubmitMessageDTO extends DTO {
/**
*
*/
private static final long serialVersionUID = -7474746101112271197L;
private String message = null;
public SubmitMessageDTO() {
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| 15.08 | 68 | 0.702918 |
66a03719e98c2f01ffc356c7f0b24f0a18ab22ac | 846 | package com.smockin.admin.persistence.migration.version;
import com.smockin.admin.persistence.dao.MigrationDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Created by gallina.
*/
@Component
public class MigrationPatch_200 implements MigrationPatch {
@Autowired
private MigrationDAO migrationDAO;
@Override
public String versionNo() {
return "2.0.0";
}
@Override
public void execute() {
migrationDAO.buildNativeQuery("DROP TABLE JMS_MOCK;")
.executeUpdate();
migrationDAO.buildNativeQuery("DROP TABLE FTP_MOCK;")
.executeUpdate();
migrationDAO.buildNativeQuery("DELETE FROM SERVER_CONFIG WHERE SERVER_TYPE IN ('JMS', 'FTP');")
.executeUpdate();
}
}
| 23.5 | 103 | 0.684397 |
9081326f7abe79bed382704e3be66ed517627cfd | 1,336 | package integration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static com.codeborne.selenide.Condition.attribute;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selectors.byText;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.closeWebDriver;
import static com.codeborne.selenide.Selenide.open;
import static com.codeborne.selenide.WebDriverRunner.isChrome;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assumptions.assumeThat;
public class MobileEmulationTest {
@BeforeEach
void setUp() {
assumeThat(isChrome()).isTrue();
closeWebDriver();
assertThat(System.getProperty("chromeoptions.mobileEmulation")).isNull();
System.setProperty("chromeoptions.mobileEmulation", "deviceName=Nexus 5");
}
@AfterEach
void tearDown() {
if (isChrome()) {
closeWebDriver();
System.clearProperty("chromeoptions.mobileEmulation");
}
}
@Test
void canOpenBrowserInMobileEmulationMode() {
open("https://selenide.org");
$(".main-menu-pages").find(byText("Javadoc"))
.shouldBe(visible)
.shouldHave(attribute("href", "https://selenide.org/javadoc.html"));
}
}
| 31.069767 | 78 | 0.75524 |
48b3dd7c89789efcd01ec2402bad927b1b60465b | 1,195 | package algoritmocyk;
import java.util.ArrayList;
public class Geradores {
private ArrayList<String> listaGeradores;
public Geradores() {
super();
this.listaGeradores = new ArrayList<>();
}
public void adicionarGeradores(String gerador){
if (!this.listaGeradores.contains(gerador)) {
this.listaGeradores.add(gerador);
}
}
public ArrayList<String> getListaGeradores() {
return listaGeradores;
}
public boolean contemElemento(String elemento){
for (int i = 0; i < this.listaGeradores.size(); i++) {
if (this.listaGeradores.get(i).equals(elemento)) {
return true;
}
}
return false;
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append("{");
for (int i = 0; i < listaGeradores.size(); i++) {
if (i != listaGeradores.size()-1) {
str.append(listaGeradores.get(i)).append(", ");
} else {
str.append(listaGeradores.get(i));
}
}
str.append("}");
return str.toString();
}
}
| 24.387755 | 63 | 0.54477 |
021954bc793781ccaedb2e8101cc69b6a60935e3 | 631 | package daggerok.domain.data;
import com.querydsl.core.types.Predicate;
import lombok.val;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.stereotype.Repository;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
@Repository
public interface DomainRepository extends JpaRepository<Domain, Long>, QueryDslPredicateExecutor<Domain> {
default Stream<Domain> filter(final Predicate predicate) {
val source = findAll(predicate).spliterator();
return StreamSupport.stream(source, false);
}
}
| 31.55 | 106 | 0.816165 |
1c3e03c3da9379a7a51a0a289be41ce2ca642049 | 5,888 | /*
* The MIT License
*
* Copyright (c) 2020 Iurii Shugalii
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.ishugaliy.allgood.consistent.hash.samples;
import org.ishugaliy.allgood.consistent.hash.ConsistentHash;
import org.ishugaliy.allgood.consistent.hash.HashRing;
import org.ishugaliy.allgood.consistent.hash.hasher.DefaultHasher;
import org.ishugaliy.allgood.consistent.hash.hasher.Hasher;
import org.ishugaliy.allgood.consistent.hash.node.Node;
import org.ishugaliy.allgood.consistent.hash.node.SimpleNode;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Sandbox allows checking consistent hash performance.
* Showing how execution time depends on the ring size and partition rate.
* <p>
*
* Case:
* 1. Build hash rings with
* {@link WorkloadBenchmarkSandbox#PARTITION_RATE}
* {@link WorkloadBenchmarkSandbox#NODES_COUNT}
* {@link WorkloadBenchmarkSandbox#HASHER}
* 2. Benchmark {@link HashRing#add(Node)} api
* 3. Benchmark {@link HashRing#locate(String)} api
* with {@link WorkloadBenchmarkSandbox#REQUEST_COUNTS}
* 4. Benchmark {@link HashRing#locate(String, int)} api
* with {@link WorkloadBenchmarkSandbox#REQUEST_COUNTS}
*
* @author Iurii Shugalii
*/
// TODO: use JMH benchmark instead - https://openjdk.java.net/projects/code-tools/jmh/
public class WorkloadBenchmarkSandbox {
private static final Hasher HASHER = DefaultHasher.MURMUR_3;
private static final int PARTITION_RATE = 1000;
private static final int NODES_COUNT = 10_000;
private static final int REQUEST_COUNTS = 1_000_000;
// nodes count to be located per request
private static final int LOCATE_NODES_COUNT = 5;
public static void main(String[] args) {
// Build hash ring
ConsistentHash<SimpleNode> ring = HashRing.<SimpleNode>newBuilder()
.partitionRate(PARTITION_RATE)
.hasher(HASHER)
.build();
System.out.println(ring);
System.out.println("-------------------------------------");
benchmarkNodesAdd(ring);
benchmarkLocate(ring);
benchmarkLocateN(ring);
}
private static void benchmarkNodesAdd(ConsistentHash<SimpleNode> ring) {
System.out.println("############# NODES ADD ############");
long start = System.currentTimeMillis();
long tmp = start;
List<SimpleNode> nodes = buildNodes();
for (int i = 0; i < nodes.size(); i++) {
ring.add(nodes.get(i));
if (i % 100 == 0) {
System.out.println(
String.format("Total nodes: [%d] - %s added in: %f .sec",
i, 100, (float) (System.currentTimeMillis() - tmp) / 100));
tmp = System.currentTimeMillis();
}
}
System.out.println("---");
System.out.println(String.format("Total nodes: [%d] - added in: %f .sec", NODES_COUNT,
(float) (System.currentTimeMillis() - start) / 1000));
System.out.println();
}
private static void benchmarkLocate(ConsistentHash<SimpleNode> ring) {
System.out.println("############# LOCATE ############");
long start = System.currentTimeMillis();
for (int i = 1; i <= REQUEST_COUNTS; i++) {
String key = UUID.randomUUID().toString();
ring.locate(key);
}
System.out.println(String.format("Total req: [%d] - located in: %f .sec", REQUEST_COUNTS,
(float) (System.currentTimeMillis() - start) / 1000));
System.out.println();
}
private static void benchmarkLocateN(ConsistentHash<SimpleNode> ring) {
System.out.println("############# LOCATE N ############");
long start = System.currentTimeMillis();
long tmp = start;
for (int i = 1; i <= REQUEST_COUNTS; i++) {
String key = UUID.randomUUID().toString();
ring.locate(key, LOCATE_NODES_COUNT);
if (i % 10_000 == 0) {
System.out.println(
String.format("Total req: [%d] - %s located in: %f .sec",
i, 100_000, (float) (System.currentTimeMillis() - tmp) / 1000));
tmp = System.currentTimeMillis();
}
}
System.out.println("---");
System.out.println(String.format("Total req: [%d] - located in: %f .sec", REQUEST_COUNTS,
(float) (System.currentTimeMillis() - start) / 1000));
System.out.println();
}
private static List<SimpleNode> buildNodes() {
return IntStream.range(0, NODES_COUNT)
.mapToObj(idx -> SimpleNode.of("aws.node" + idx + ".api." + Math.round(Math.pow(idx, 2))))
.collect(Collectors.toList());
}
}
| 39.516779 | 106 | 0.634001 |
7e6d6993bea34d689b3bdc1c71bc12be171a749a | 128 | package telran.tests.perfomance;
public interface JoinStringsInterface {
String join(String[] strings, String delimiter) ;
}
| 18.285714 | 50 | 0.789063 |
b890d260d596739713a3bb30d5e8b4a50f7804ec | 679 | package io.github.ggface.api.utils;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
/**
* Класс для работы со строками.
*
* @author Ivan Novikov on 2018-07-31.
*/
public final class StringUtils {
private StringUtils() {
}
/**
* Возвращает не-{@code null}-строку.
*
* @param nullableString Строка, которая может быть {@code null}
* @return {@code nullableString} или пустая строка, но не {@code null}.
*/
@NonNull
public static String nonNull(@Nullable String nullableString) {
if (nullableString == null) {
return "";
}
return nullableString;
}
} | 22.633333 | 76 | 0.63623 |
348fb1cf1095a0df4f29dae01c2140d6ac8b0d92 | 37,257 | /*
* Copyright (c) 2017, 2018 Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.helidon.config;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import io.helidon.common.CollectionsHelper;
import static io.helidon.config.Config.Type.OBJECT;
import java.util.function.Function;
import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/**
* Tests {@link Config} API in case the node is {@link Config.Type#OBJECT} type,
* i.e. {@link ConfigObjectImpl}.
*/
public class ConfigObjectImplTest extends AbstractConfigImplTest {
public static Stream<TestContext> initParams() {
return Stream.of(
// use root config properties
new TestContext("", 1, true),
new TestContext("", 1, false),
// and object properties
new TestContext("object-1", 2, true),
new TestContext("object-1", 2, false),
// and sub-object properties
new TestContext("object-1.object-2", 3, true),
new TestContext("object-1.object-2", 3, false),
// and object in a list properties
new TestContext("list-1.1", 3, true),
new TestContext("list-1.1", 3, false)
);
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testTypeExists(TestContext context) {
init(context);
assertThat(config().exists(), is(true));
assertThat(config().type().exists(), is(true));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testTypeIsLeaf(TestContext context) {
init(context);
assertThat(config().isLeaf(), is(false));
assertThat(config().type().isLeaf(), is(false));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testValue(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.value());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalString(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asOptionalString());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testNodeList(TestContext context) {
init(context);
assertThat(nodeNames(config().nodeList().get()),
containsInAnyOrder(objectNames()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptional(TestContext context) {
init(context);
assertThat(config().asOptional(ObjectConfigBean.class).get(),
is(new ObjectConfigBean("fromConfig", "key:" + nodeName())));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalList(TestContext context) {
init(context);
assertThat(config().asOptionalList(ObjectConfigBean.class).get(),
containsInAnyOrder(expectedObjectConfigBeans()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalStringList(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asOptionalStringList());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapOptionalWithFunction(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.mapOptional(ValueConfigBean::fromString));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapOptionalWithConfigMapper(TestContext context) {
init(context);
assertThat(config().mapOptional(ObjectConfigBean::fromConfig).get(),
is(new ObjectConfigBean("fromConfig", "key:" + nodeName())));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalInt(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asOptionalInt());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalBoolean(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asOptionalBoolean());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalLong(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asOptionalLong());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalDouble(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asOptionalDouble());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapOptionalListWithFunction(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.mapOptionalList(ValueConfigBean::fromString));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapOptionalListWithConfigMapper(TestContext context) {
init(context);
assertThat(config().mapOptionalList(ObjectConfigBean::fromConfig).get(),
containsInAnyOrder(expectedObjectConfigBeans()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAs(TestContext context) {
init(context);
assertThat(config().as(ObjectConfigBean.class), is(new ObjectConfigBean("fromConfig", "key:" + nodeName())));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsWithDefault(TestContext context) {
init(context);
assertThat(config().as(ObjectConfigBean.class, ObjectConfigBean.EMPTY),
is(new ObjectConfigBean("fromConfig", "key:" + nodeName())));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapWithFunction(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.map(ValueConfigBean::fromString));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapWithFunctionAndDefault(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.map(ValueConfigBean::fromString, ObjectConfigBean.EMPTY));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapWithConfigMapper(TestContext context) {
init(context);
assertThat(config().map(ObjectConfigBean::fromConfig),
is(new ObjectConfigBean("fromConfig", "key:" + nodeName())));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapWithConfigMapperAndDefault(TestContext context) {
init(context);
assertThat(config().map(ObjectConfigBean::fromConfig, ObjectConfigBean.EMPTY),
is(new ObjectConfigBean("fromConfig", "key:" + nodeName())));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsList(TestContext context) {
init(context);
assertThat(config().asList(ObjectConfigBean.class),
containsInAnyOrder(expectedObjectConfigBeans()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsListWithDefault(TestContext context) {
init(context);
assertThat(config().asList(ObjectConfigBean.class, CollectionsHelper.listOf(ObjectConfigBean.EMPTY)),
containsInAnyOrder(expectedObjectConfigBeans()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapListWithFunction(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.mapList(ValueConfigBean::fromString));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapListWithFunctionAndDefault(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.mapList(ValueConfigBean::fromString, CollectionsHelper.listOf(ValueConfigBean.EMPTY)));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapListWithConfigMapper(TestContext context) {
init(context);
assertThat(config().mapList(ObjectConfigBean::fromConfig),
containsInAnyOrder(expectedObjectConfigBeans()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapListWithConfigMapperAndDefault(TestContext context) {
init(context);
assertThat(config().mapList(ObjectConfigBean::fromConfig, CollectionsHelper.listOf(ObjectConfigBean.EMPTY)),
containsInAnyOrder(expectedObjectConfigBeans()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsString(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asString());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsStringWithDefault(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asString("default value"));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsBoolean(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asBoolean());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsBooleanWithDefault(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asBoolean(true));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsInt(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asInt());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsIntWithDefault(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asInt(42));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsLong(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asLong());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsLongWithDefault(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asLong(23));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsDouble(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asDouble());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsDoubleWithDefault(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asDouble(Math.PI));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsStringList(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asStringList());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsStringListWithDefault(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asStringList(CollectionsHelper.listOf("default", "value")));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsNodeList(TestContext context) {
init(context);
assertThat(nodeNames(config().asNodeList()),
containsInAnyOrder(objectNames()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsNodeListWithDefault(TestContext context) {
init(context);
assertThat(nodeNames(config().asNodeList(CollectionsHelper.listOf(Config.empty()))),
containsInAnyOrder(objectNames()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testTimestamp(TestContext context) {
init(context);
testTimestamp(config());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testDetach(TestContext context) {
init(context);
Config detached = config().detach();
assertThat(detached.type(), is(OBJECT));
assertThat(detached.key().toString(), is(""));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testNode(TestContext context) {
init(context);
AtomicBoolean called = new AtomicBoolean(false);
config()
.node()
.ifPresent(node -> {
assertThat(node.key(), is(key()));
called.set(true);
});
assertThat(called.get(), is(true));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testIfExists(TestContext context) {
init(context);
AtomicBoolean called = new AtomicBoolean(false);
config().ifExists(
node -> {
assertThat(node.key(), is(key()));
called.set(true);
});
assertThat(called.get(), is(true));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testIfExistsOrElse(TestContext context) {
init(context);
AtomicBoolean called = new AtomicBoolean(false);
config().ifExistsOrElse(
node -> {
assertThat(node.key(), is(key()));
called.set(true);
},
() -> fail("Expected config not found"));
assertThat(called.get(), is(true));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalMap(TestContext context) {
init(context);
assertThat(config().asOptionalMap().get().entrySet(), hasSize(subLeafs()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsMap(TestContext context) {
init(context);
assertThat(config().asMap().entrySet(), hasSize(subLeafs()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsMapWithDefault(TestContext context) {
init(context);
assertThat(config().asMap(CollectionsHelper.mapOf()).entrySet(), hasSize(subLeafs()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testTraverseWithPredicate(TestContext context) {
init(context);
List<Config.Key> allSubKeys = config()
// ignore whole list nodes
.traverse(node -> node.type() != Config.Type.LIST)
.map(Config::key)
.collect(Collectors.toList());
assertThat(allSubKeys, hasSize(subNodesNoLists()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testTypeExistsSupplier(TestContext context) {
init(context);
assertThat(config().nodeSupplier().get().get().exists(), is(true));
assertThat(config().nodeSupplier().get().get().type().exists(), is(true));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testTypeIsLeafSupplier(TestContext context) {
init(context);
assertThat(config().nodeSupplier().get().get().isLeaf(), is(false));
assertThat(config().nodeSupplier().get().get().type().isLeaf(), is(false));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testOptionalStringSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asOptionalStringSupplier().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testNodeListSupplier(TestContext context) {
init(context);
assertThat(nodeNames(config().asNodeListSupplier().get()),
containsInAnyOrder(objectNames()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalSupplier(TestContext context) {
init(context);
assertThat(config().asOptionalSupplier(ObjectConfigBean.class).get().get(),
is(new ObjectConfigBean("fromConfig", "key:" + nodeName())));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalListSupplier(TestContext context) {
init(context);
assertThat(config().asOptionalListSupplier(ObjectConfigBean.class).get().get(),
containsInAnyOrder(expectedObjectConfigBeans()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalStringListSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asOptionalStringListSupplier().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapOptionalWithFunctionSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.mapOptionalSupplier(ValueConfigBean::fromString).get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapOptionalWithConfigMapperSupplier(TestContext context) {
init(context);
assertThat(config().mapOptionalSupplier(ObjectConfigBean::fromConfig).get().get(),
is(new ObjectConfigBean("fromConfig", "key:" + nodeName())));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalBooleanSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asOptionalBooleanSupplier().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalIntSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asOptionalIntSupplier().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalLongSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asOptionalLongSupplier().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalDoubleSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asOptionalDoubleSupplier().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapOptionalListWithFunctionSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.mapOptionalListSupplier(ValueConfigBean::fromString).get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapOptionalListWithConfigMapperSupplier(TestContext context) {
init(context);
assertThat(config().mapOptionalListSupplier(ObjectConfigBean::fromConfig).get().get(),
containsInAnyOrder(expectedObjectConfigBeans()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsSupplier(TestContext context) {
init(context);
assertThat(config().asSupplier(ObjectConfigBean.class).get(),
is(new ObjectConfigBean("fromConfig", "key:" + nodeName())));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsWithDefaultSupplier(TestContext context) {
init(context);
assertThat(config().asSupplier(ObjectConfigBean.class, ObjectConfigBean.EMPTY).get(),
is(new ObjectConfigBean("fromConfig", "key:" + nodeName())));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapWithFunctionSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.mapSupplier(ValueConfigBean::fromString).get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapWithFunctionAndDefaultSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.mapSupplier(ValueConfigBean::fromString, ObjectConfigBean.EMPTY).get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapWithConfigMapperSupplier(TestContext context) {
init(context);
assertThat(config().mapSupplier(ObjectConfigBean::fromConfig).get(),
is(new ObjectConfigBean("fromConfig", "key:" + nodeName())));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapWithConfigMapperAndDefaultSupplier(TestContext context) {
init(context);
assertThat(config().mapSupplier(ObjectConfigBean::fromConfig, ObjectConfigBean.EMPTY).get(),
is(new ObjectConfigBean("fromConfig", "key:" + nodeName())));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsListSupplier(TestContext context) {
init(context);
assertThat(config().asListSupplier(ObjectConfigBean.class).get(),
containsInAnyOrder(expectedObjectConfigBeans()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsListWithDefaultSupplier(TestContext context) {
init(context);
assertThat(config().asListSupplier(ObjectConfigBean.class, CollectionsHelper.listOf(ObjectConfigBean.EMPTY)).get(),
containsInAnyOrder(expectedObjectConfigBeans()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapListWithFunctionSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.mapListSupplier(ValueConfigBean::fromString).get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapListWithFunctionAndDefaultSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.mapListSupplier(ValueConfigBean::fromString, CollectionsHelper.listOf(ValueConfigBean.EMPTY)).get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapListWithConfigMapperSupplier(TestContext context) {
init(context);
assertThat(config().mapListSupplier(ObjectConfigBean::fromConfig).get(),
containsInAnyOrder(expectedObjectConfigBeans()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testMapListWithConfigMapperAndDefaultSupplier(TestContext context) {
init(context);
assertThat(config().mapListSupplier(ObjectConfigBean::fromConfig, CollectionsHelper.listOf(ObjectConfigBean.EMPTY)).get(),
containsInAnyOrder(expectedObjectConfigBeans()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsStringSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asStringSupplier().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsStringWithDefaultSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asStringSupplier("default value").get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsBooleanSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asBooleanSupplier().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsBooleanWithDefaultSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asBooleanSupplier(true).get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsIntSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asIntSupplier().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsIntWithDefaultSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asIntSupplier(42).get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsLongSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asLongSupplier().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsLongWithDefaultSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asLongSupplier(23).get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsDoubleSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asDoubleSupplier().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsDoubleWithDefaultSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asDoubleSupplier(Math.PI).get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsStringListSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asStringListSupplier().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsStringListWithDefaultSupplier(TestContext context) {
init(context);
getConfigAndExpectException(config -> config.asStringListSupplier(CollectionsHelper.listOf("default", "value")).get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsNodeListSupplier(TestContext context) {
init(context);
assertThat(nodeNames(config().asNodeListSupplier().get()),
containsInAnyOrder(objectNames()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsNodeListWithDefaultSupplier(TestContext context) {
init(context);
assertThat(nodeNames(config().asNodeListSupplier(CollectionsHelper.listOf(Config.empty())).get()),
containsInAnyOrder(objectNames()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testTimestampSupplier(TestContext context) {
init(context);
testTimestamp(config().nodeSupplier().get().get());
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testDetachSupplier(TestContext context) {
init(context);
Config detached = config().detach().nodeSupplier().get().get();
assertThat(detached.type(), is(OBJECT));
assertThat(detached.key().toString(), is(""));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testNodeSupplier(TestContext context) {
init(context);
AtomicBoolean called = new AtomicBoolean(false);
config()
.nodeSupplier()
.get()
.ifPresent(node -> {
assertThat(node.key(), is(key()));
called.set(true);
});
assertThat(called.get(), is(true));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testIfExistsSupplier(TestContext context) {
init(context);
AtomicBoolean called = new AtomicBoolean(false);
config()
.nodeSupplier()
.get()
.get()
.ifExists(
node -> {
assertThat(node.key(), is(key()));
called.set(true);
});
assertThat(called.get(), is(true));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testIfExistsOrElseSupplier(TestContext context) {
init(context);
AtomicBoolean called = new AtomicBoolean(false);
config()
.nodeSupplier()
.get()
.get()
.ifExistsOrElse(
node -> {
assertThat(node.key(), is(key()));
called.set(true);
},
() -> fail("Expected config not found"));
assertThat(called.get(), is(true));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsOptionalMapSupplier(TestContext context) {
init(context);
assertThat(config().asOptionalMapSupplier().get().get().entrySet(), hasSize(subLeafs()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsMapSupplier(TestContext context) {
init(context);
assertThat(config().asMapSupplier().get().entrySet(), hasSize(subLeafs()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testAsMapWithDefaultSupplier(TestContext context) {
init(context);
assertThat(config().asMapSupplier(CollectionsHelper.mapOf()).get().entrySet(), hasSize(subLeafs()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testTraverseWithPredicateSupplier(TestContext context) {
init(context);
List<Config.Key> allSubKeys = config()
.nodeSupplier()
.get()
.get()
// ignore whole list nodes
.traverse(node -> node.type() != Config.Type.LIST)
.map(Config::key)
.collect(Collectors.toList());
assertThat(allSubKeys, hasSize(subNodesNoLists()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testTraverseSupplier(TestContext context) {
init(context);
List<Config.Key> allSubKeys = config()
.nodeSupplier()
.get()
.get()
.traverse()
.map(Config::key)
.collect(Collectors.toList());
assertThat(allSubKeys, hasSize(subNodes()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testToStringSupplier(TestContext context) {
init(context);
/*
VALUE object-2.double-3
OBJECT object-2.object-3
LIST object-2.str-list-3
VALUE object-2.long-3
VALUE object-2.text-3
VALUE object-2.bool-3
LIST object-2.list-3
VALUE object-2.int-3
*/
assertThat(config().nodeSupplier().get().get().toString(), both(startsWith("["))
.and(endsWith(key() + "] OBJECT (members: 8)")));
}
/**
* Count number of sub-nodes.
*
* @param levelCount number of nodes on single level
* @param includeLists if count also LIST trees
* @return summary count
*/
private int subCount(int levelCount, boolean includeLists) {
//TODO improved "computation"
switch (level()) {
case MAX_LEVELS:
return levelCount;
case MAX_LEVELS - 1:
return (includeLists ? 3 : 2) * levelCount;
case MAX_LEVELS - 2:
return (includeLists ? 7 : 3) * levelCount;
default:
break;
}
return -1;
}
private int subNodes() {
/*
VALUE object-2.double-3
OBJECT object-2.object-3
LIST object-2.str-list-3
VALUE object-2.str-list-3.0
VALUE object-2.str-list-3.1
VALUE object-2.str-list-3.2
VALUE object-2.long-3
VALUE object-2.text-3
VALUE object-2.bool-3
LIST object-2.list-3
VALUE object-2.int-3
*/
return subCount(11, true);
}
private int subNodesNoLists() {
/*
VALUE object-2.double-3
OBJECT object-2.object-3
VALUE object-2.long-3
VALUE object-2.text-3
VALUE object-2.bool-3
VALUE object-2.int-3
*/
return subCount(6, false);
}
private int subLeafs() {
/*
VALUE object-2.double-3
VALUE object-2.str-list-3.0
VALUE object-2.str-list-3.1
VALUE object-2.str-list-3.2
VALUE object-2.long-3
VALUE object-2.text-3
VALUE object-2.bool-3
VALUE object-2.int-3
*/
return subCount(8, true);
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testTraverse(TestContext context) {
init(context);
List<Config.Key> allSubKeys = config()
.traverse()
.map(Config::key)
.collect(Collectors.toList());
assertThat(allSubKeys, hasSize(subNodes()));
}
@Override
@MethodSource("initParams")
@ParameterizedTest
public void testToString(TestContext context) {
init(context);
/*
VALUE object-2.double-3
OBJECT object-2.object-3
LIST object-2.str-list-3
VALUE object-2.long-3
VALUE object-2.text-3
VALUE object-2.bool-3
LIST object-2.list-3
VALUE object-2.int-3
*/
assertThat(config().toString(), both(startsWith("["))
.and(endsWith(key() + "] OBJECT (members: 8)")));
}
//
// helper
//
private <T> void getConfigAndExpectException(Function<Config, T> op) {
Config config = config();
ConfigMappingException ex = assertThrows(ConfigMappingException.class, () -> {
op.apply(config);
});
assertTrue(ex.getMessage().contains("'" + config.key() + "'"));
}
protected Config config() {
return config("");
}
private Config.Key key() {
return config().key();
}
private String[] objectNames() {
return objectNames(level()).toArray(new String[0]);
}
private String nodeName() {
return nodeName(config());
}
private ObjectConfigBean[] expectedObjectConfigBeans() {
return CollectionsHelper.listOf(
new ObjectConfigBean("fromConfig", "key:double-" + level() + "@VALUE"),
new ObjectConfigBean("fromConfig", "key:bool-" + level() + "@VALUE"),
new ObjectConfigBean("fromConfig", "key:object-" + level() + "@OBJECT"),
new ObjectConfigBean("fromConfig", "key:int-" + level() + "@VALUE"),
new ObjectConfigBean("fromConfig", "key:text-" + level() + "@VALUE"),
new ObjectConfigBean("fromConfig", "key:str-list-" + level() + "@LIST"),
new ObjectConfigBean("fromConfig", "key:long-" + level() + "@VALUE"),
new ObjectConfigBean("fromConfig", "key:list-" + level() + "@LIST"))
.toArray(new ObjectConfigBean[0]);
}
}
| 32.397391 | 154 | 0.64294 |
50c09805d911866613ed2aa35e6c7169ac0a5763 | 1,201 | package com.qidao.qidao.server.server.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ServerAddReq {
/**
* 标题
*/
private String title;
/**
* 需求领域
*/
private Long specAreaId;
/**
* 发布人
*/
private Long memberIdPartyA;
/**
* 研发经费
*/
private Long specAmountId;
/**
* 地址省编码
*/
private Integer addressProvinceId;
/**
* 地址省名字
*/
private String addressProvinceName;
/**
* 地址市编码
*/
private Integer addressCityId;
/**
* 地址市名字
*/
private String addressCityName;
/**
* 地址县编码
*/
private Integer addressAreaId;
/**
* 地址县名字
*/
private String addressAreaName;
/**
* 期望解决时间
*/
private String solutionTime;
/**
* 描述
*/
private String description;
/**
* 描述文件地址
*/
private String url;
}
| 14.297619 | 60 | 0.590341 |
1c34b5a45fb37dd312554aad64a17b808c0bcb7f | 3,208 | /*
* 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.aliyuncs.aliyuncvc.transform.v20191030;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.aliyuncvc.model.v20191030.ListUsersResponse;
import com.aliyuncs.aliyuncvc.model.v20191030.ListUsersResponse.Data;
import com.aliyuncs.aliyuncvc.model.v20191030.ListUsersResponse.Data.UserInfo;
import com.aliyuncs.transform.UnmarshallerContext;
public class ListUsersResponseUnmarshaller {
public static ListUsersResponse unmarshall(ListUsersResponse listUsersResponse, UnmarshallerContext _ctx) {
listUsersResponse.setRequestId(_ctx.stringValue("ListUsersResponse.RequestId"));
listUsersResponse.setErrorCode(_ctx.integerValue("ListUsersResponse.ErrorCode"));
listUsersResponse.setMessage(_ctx.stringValue("ListUsersResponse.Message"));
listUsersResponse.setSuccess(_ctx.booleanValue("ListUsersResponse.Success"));
Data data = new Data();
data.setTotalCount(_ctx.integerValue("ListUsersResponse.Data.TotalCount"));
data.setPageSize(_ctx.integerValue("ListUsersResponse.Data.PageSize"));
data.setPageNumber(_ctx.integerValue("ListUsersResponse.Data.PageNumber"));
List<UserInfo> userInfos = new ArrayList<UserInfo>();
for (int i = 0; i < _ctx.lengthValue("ListUsersResponse.Data.UserInfos.Length"); i++) {
UserInfo userInfo = new UserInfo();
userInfo.setCreateTime(_ctx.longValue("ListUsersResponse.Data.UserInfos["+ i +"].CreateTime"));
userInfo.setGroupName(_ctx.stringValue("ListUsersResponse.Data.UserInfos["+ i +"].GroupName"));
userInfo.setUserName(_ctx.stringValue("ListUsersResponse.Data.UserInfos["+ i +"].UserName"));
userInfo.setGroupId(_ctx.stringValue("ListUsersResponse.Data.UserInfos["+ i +"].GroupId"));
userInfo.setDepartName(_ctx.stringValue("ListUsersResponse.Data.UserInfos["+ i +"].DepartName"));
userInfo.setDepartId(_ctx.stringValue("ListUsersResponse.Data.UserInfos["+ i +"].DepartId"));
userInfo.setUserEmail(_ctx.stringValue("ListUsersResponse.Data.UserInfos["+ i +"].UserEmail"));
userInfo.setUserTel(_ctx.stringValue("ListUsersResponse.Data.UserInfos["+ i +"].UserTel"));
userInfo.setUserMobile(_ctx.stringValue("ListUsersResponse.Data.UserInfos["+ i +"].UserMobile"));
userInfo.setUserAvatarUrl(_ctx.stringValue("ListUsersResponse.Data.UserInfos["+ i +"].UserAvatarUrl"));
userInfo.setJobName(_ctx.stringValue("ListUsersResponse.Data.UserInfos["+ i +"].JobName"));
userInfo.setUserId(_ctx.stringValue("ListUsersResponse.Data.UserInfos["+ i +"].UserId"));
userInfos.add(userInfo);
}
data.setUserInfos(userInfos);
listUsersResponse.setData(data);
return listUsersResponse;
}
} | 50.920635 | 108 | 0.767456 |
2eeb6ec0c2d70dbbb2f995bdcaed56938cc8186a | 250 | package com.example.habitapp.enums;
/**
* This is the enum for the types of goals that a user can give to a habit.
*
* @author Maximilian Ta
* @version 0.1
*/
public enum Goal {
DAILY_STREAK, WEEKLY_STREAK, MONTHLY_STREAK, AMOUNT, NONE;
}
| 19.230769 | 75 | 0.7 |
769f0f1b4b843a8d0a92f1522af00e1ba5b20cbb | 1,807 | package org.zalando.baigan.s3;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.model.DecryptRequest;
import com.amazonaws.services.kms.model.DecryptResult;
import org.junit.jupiter.api.Test;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static java.nio.ByteBuffer.wrap;
class DecryptingS3ObjectSupplierTest {
@Test
void passesThroughUnencryptedValues() {
final AWSKMS client = mock(AWSKMS.class);
final DecryptingS3ObjectSupplier unit = new DecryptingS3ObjectSupplier(client, () -> "not-so-secret");
assertEquals("not-so-secret", unit.get());
verifyNoMoreInteractions(client);
}
@Test
void decryptsEncodedCipher() {
final String cipher = "secret";
final String plaintext = "plaintext";
final AWSKMS client = buildClient(plaintext, cipher);
final String encrypted = "aws:kms:" + Base64.getEncoder().encodeToString(cipher.getBytes());
final DecryptingS3ObjectSupplier unit = new DecryptingS3ObjectSupplier(client, () -> encrypted);
assertEquals(plaintext, unit.get());
}
private AWSKMS buildClient(final String plaintext, final String cipher) {
final AWSKMS client = mock(AWSKMS.class);
final DecryptResult result = new DecryptResult();
result.setPlaintext(wrap(plaintext.getBytes()));
when(client.decrypt(argThat(argument ->
argument.equals(new DecryptRequest().withCiphertextBlob(wrap(cipher.getBytes()))))))
.thenReturn(result);
return client;
}
} | 38.446809 | 110 | 0.718318 |
3ad93c6b8994c23fd5005b56743258f0a8e87159 | 1,252 | /*******************************************************************************
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* 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 hr.fer.zemris.vhdllab.platform.manager.editor;
import java.util.List;
public interface EditorContainer {
void add(Editor editor);
void remove(Editor editor);
int indexOf(Editor editor);
Editor getSelected();
void setSelected(Editor editor);
void setSelected(int index);
boolean isSelected(Editor editor);
List<Editor> getAll();
List<Editor> getAllButSelected();
}
| 29.809524 | 80 | 0.640575 |
2f28a1d41eeb68625ee54fad5d77eb0918b557e6 | 1,575 | package ch.bernmobil.vibe.shared;
import org.junit.Assert;
import java.sql.Timestamp;
public class TestHelper {
private final MockProvider.QueryCollector queryCollector;
public TestHelper(MockProvider.QueryCollector queryCollector) {
this.queryCollector = queryCollector;
}
void assertBindings(Object[][] expectedBindings) {
assertBindings(expectedBindings, 1000);
}
void assertBindings(Object[][] expectedBindings, long timestampDelta) {
Assert.assertEquals(expectedBindings.length, queryCollector.getBindings().size());
for(int i = 0; i < expectedBindings.length; i++) {
Object[] queryBindings = expectedBindings[i];
Assert.assertEquals(expectedBindings[i].length, queryCollector.getBindings().get(i).size());
for(int j = 0; j < queryBindings.length; j++) {
if(queryBindings[j] instanceof Timestamp) {
Assert.assertEquals(((Timestamp)expectedBindings[i][j]).getTime(),
((Timestamp)queryCollector.getBindings().get(i).get(j)).getTime(), timestampDelta);
} else {
Assert.assertEquals(expectedBindings[i][j], queryBindings[j]);
}
}
}
}
void assertQueries(String[] expectedQueries) {
Assert.assertEquals(expectedQueries.length, queryCollector.getQueries().size());
Assert.assertArrayEquals(expectedQueries,
queryCollector.getQueries().toArray(new String[queryCollector.getQueries().size()]));
}
}
| 38.414634 | 111 | 0.646349 |
7a6d7f5eb71b01c4ee43e369644c2e8d4fd9b21b | 276 | package com.bizzan.bitrade.model.screen;
import lombok.Data;
@Data
public class ExchangeTradeScreen {
private String buyerUsername ;
private String sellerUsername ;
private String buyOrderId ;
private String sellOrderId ;
private String symbol ;
}
| 14.526316 | 40 | 0.735507 |
a8fd429e04cb5657e751b0695de4232c3533e611 | 638 | package top.chenqwwq.leetcode.biweek._62._3;
/**
* @author: chenqwwq
* @date: 2021/10/4 9:50 下午
**/
public class Solution {
public int maxConsecutiveAnswers(String answerKey, int k) {
// 滑动窗口
if (answerKey == null || answerKey.length() == 0) {
return 0;
}
final int n = answerKey.length();
int ans = 1;
int left = 0, right = 0,tc = 0,fc = 0;
while (right < n){
if(answerKey.charAt(right++) == 'T'){
tc++;
}else {
fc++;
}
if(tc <= k || fc <= k){
ans = Math.max(ans,tc + fc);
}else{
if(answerKey.charAt(left++) == 'T'){
tc--;
}else{
fc--;
}
}
}
return ans;
}
}
| 18.228571 | 60 | 0.529781 |
0ebbf9b5d991a3c08666226d897f5c7821537743 | 337 | package org.springframework.cloud.sleuth.zipkin;
/**
* Contract for reporting Zipkin spans to Zipkin.
*
* @author Adrian Cole
* @since 1.0.0
*/
public interface ZipkinSpanReporter {
/**
* Receives completed spans from {@link ZipkinSpanListener} and submits them to a Zipkin
* collector.
*/
void report(zipkin.Span span);
}
| 21.0625 | 89 | 0.718101 |
9e06a27c3b8607486295862185fbad41b977279b | 529 | package com.skyrimmarket.backend.model;
import lombok.*;
import javax.persistence.*;
import static javax.persistence.GenerationType.IDENTITY;
@Data
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Builder
@Entity
@Table(name = "order_status")
public class OrderStatus {
@Id
@GeneratedValue(strategy = IDENTITY)
@EqualsAndHashCode.Include()
private Long id;
@NonNull
@Column(nullable = false, unique = true)
private String name;
}
| 19.592593 | 56 | 0.758034 |
0611cce59a5ca0599b8b4f39d954a886ff507da3 | 398 | package edu.ksu.cs.malicious;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MalOutgoingCallReceiver extends BroadcastReceiver {
public MalOutgoingCallReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
String phnNm = "7110006217";
setResultData(phnNm);
}
}
| 22.111111 | 64 | 0.736181 |
30e26557009f188ebd037e98b331a8f2f99b7078 | 621 | package org.polyglotted.crypto.digest;
import static org.junit.Assert.assertEquals;
import static org.polyglotted.crypto.TestUtils.asStream;
import org.junit.Test;
public class Sha1DigestTest {
@Test
public void testCreateInputStream() {
String checksum = new Sha1Digest().create(asStream("files/plain-text.properties"));
assertEquals("f5331248330179971e299cd98ebb2619010ca440", checksum);
}
@Test
public void testCreateString() {
String checksum = new Sha1Digest().create("test value");
assertEquals("ca29587b51dca2169155f72187fa4ebc738526e2", checksum);
}
}
| 28.227273 | 91 | 0.732689 |
7d2ec87b4143bcecd5dc7c27cb28d39daa65b456 | 8,593 | /**
* Copyright Vitalii Rudenskyi (vrudenskyi@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mckesson.kafka.connect.salesforce;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigDef.Importance;
import org.apache.kafka.common.config.ConfigDef.Type;
import org.apache.kafka.connect.source.SourceRecord;
import org.apache.kafka.connect.transforms.util.SimpleConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.force.api.DescribeSObject;
import com.force.api.DescribeSObject.Field;
import com.mckesson.kafka.connect.source.APIClientException;
public class SobjectPollableAPIClient extends SalesforceAPIClient {
private static final Logger log = LoggerFactory.getLogger(EventLogPollableAPIClient.class);
public static final String SF_SOBJECTS_CONFIG = "sfdc.sobjects";
public static final String SF_QUERY_LIMIT_CONFIG = "sfdc.queryLimit";
public static final int SF_QUERY_LIMIT_DEFAULT = 1000;
private static final ConfigDef CLIENT_CONFIG_DEF = new ConfigDef()
.define(SF_SOBJECTS_CONFIG, Type.LIST, ConfigDef.NO_DEFAULT_VALUE, Importance.HIGH, "SObjects to read")
.define(SF_QUERY_LIMIT_CONFIG, Type.INT, SF_QUERY_LIMIT_DEFAULT, Importance.LOW, "Query limit");
public static final String SOBJECT_NAME_CONFIG = "soName";
public static final String SOBJECT_QUERY_CONFIG = "soql";
public static final String SOBJECT_FIELDS_CONFIG = "fields";
public static final String SOBJECT_ORDER_BY_CONFIG = "orderBy";
private static final ConfigDef SOBJECT_CONFIG_DEF = new ConfigDef()
.define(SOBJECT_NAME_CONFIG, Type.STRING, null, Importance.MEDIUM, "SObjectname")
.define(SOBJECT_QUERY_CONFIG, Type.STRING, null, Importance.MEDIUM, "SObject soql")
.define(SOBJECT_FIELDS_CONFIG, Type.LIST, null, Importance.MEDIUM, "SObject fields")
.define(SOBJECT_ORDER_BY_CONFIG, Type.STRING, null, Importance.MEDIUM, "SObject order/trck by field");
private static final String PARTITION_NAME_KEY = "_sObjectName";
private static final String PARTITION_QUERY_KEY = "_sObjectQuery";
private static final String PARTITION_ORDER_BY_KEY = "_sObjectOrderBy";
private static final String OFFSET_LOG_TIME_KEY = "__LastModifiedDate";
private static final String HEADER_SOBJECT_NAME = "sfdc.sobject";
private SimpleConfig clientConf;
private List<String> sobjects;
private Integer queryLimit;
@Override
public void configure(Map<String, ?> configs) {
super.configure(configs);
this.clientConf = new SimpleConfig(CLIENT_CONFIG_DEF, configs);
this.sobjects = clientConf.getList(SF_SOBJECTS_CONFIG);
this.queryLimit = clientConf.getInt(SF_QUERY_LIMIT_CONFIG);
}
@Override
public List<SourceRecord> poll(String topic, Map<String, Object> partition, Map<String, Object> offset, int itemsToPoll, AtomicBoolean stop) throws APIClientException {
log.debug("Executiong poll for sObject: {}, with offset: {}", partition.get(PARTITION_NAME_KEY), offset);
String soql = partition.get(PARTITION_QUERY_KEY)
.toString()
.replaceAll("\\{offset\\}", offset.get(OFFSET_LOG_TIME_KEY).toString())
.replaceAll("\\{limit\\}", "" + Math.min(itemsToPoll, queryLimit));
List<Map> qr = executeQuery(soql, offset, Map.class);
if (qr.size() == 0) {
log.debug("No new records for:{}", partition.get(PARTITION_NAME_KEY));
return Collections.emptyList();
}
List<SourceRecord> pollResult = new ArrayList<>(qr.size());
for (Map m : qr) {
try {
SourceRecord rec = new SourceRecord(partition, offset, topic, null, null, null, jacksonObjectMapper.writeValueAsString(m));
rec.headers().addString(HEADER_SOBJECT_NAME, partition.get(PARTITION_NAME_KEY).toString());
pollResult.add(rec);
} catch (JsonProcessingException ex) {
SourceRecord failedRec = new SourceRecord(partition, offset, topic, null, null, null, m.toString());
failedRec.headers().addBoolean("failed", true);
failedRec.headers().addString("errorMsg", ex.getMessage());
pollResult.add(failedRec);
}
}
String newoffset = qr.get(qr.size() - 1).get(partition.get(PARTITION_ORDER_BY_KEY)).toString();
log.debug("Offset for {} updated to: {}", partition.get(PARTITION_NAME_KEY), newoffset);
offset.put(OFFSET_LOG_TIME_KEY, newoffset);
return pollResult;
}
@Override
public List<Map<String, Object>> partitions() throws APIClientException {
log.debug("Create partitions for:{}", sobjects);
List<Map<String, Object>> partitions = new ArrayList<>();
for (String soAlias : sobjects) {
SimpleConfig soConf = new SimpleConfig(SOBJECT_CONFIG_DEF, clientConf.originalsWithPrefix(SF_SOBJECTS_CONFIG + "." + soAlias + "."));
String soName = StringUtils.isNotBlank(soConf.getString(SOBJECT_NAME_CONFIG)) ? soConf.getString(SOBJECT_NAME_CONFIG) : soAlias;
List<String> soFields = soConf.getList(SOBJECT_FIELDS_CONFIG);
String soOrderBy = soConf.getString(SOBJECT_ORDER_BY_CONFIG);
String soQuery = soConf.getString(SOBJECT_QUERY_CONFIG);
Map<String, Object> p = buildPartition(soName, soFields, soOrderBy, soQuery);
log.debug("Created partition for alias: {} => {}", soAlias, p);
partitions.add(p);
}
return partitions;
}
private Map<String, Object> buildPartition(String soName, List<String> soFields, String soOrderBy, String soQuery) throws APIClientException {
if (StringUtils.isBlank(soName)) {
throw new IllegalArgumentException("sObject name can not be blank");
}
DescribeSObject descr = null;
if (soFields == null || soFields.size() == 0 || StringUtils.isBlank(soOrderBy)) {
descr = forceApi.describeSObject(soName);
}
String selectedOrderBy = soOrderBy;
if (StringUtils.isBlank(selectedOrderBy)) {
//either LastModifiedDate or 'last of datetime type' will be selected
for (Field f : descr.getFields()) {
if ("LastModifiedDate".equals(f.getName())) {
selectedOrderBy = "LastModifiedDate";
break; //LastModifiedDate is always used if available
}
if ("datetime".equals(f.getType())) {
selectedOrderBy = f.getName();
}
}
}
if (StringUtils.isBlank(selectedOrderBy)) {
throw new APIClientException("Failed to find 'orderBy' for " + soName);
}
//use or find fields from descr
LinkedHashSet<String> selectedFields;
if (soFields != null && soFields.size() > 0) {
selectedFields = new LinkedHashSet<>(soFields);
} else {
selectedFields = new LinkedHashSet<>(descr.getFields().size());
descr.getFields().forEach(e -> {
selectedFields.add(e.getName());
});
}
//build query
String selectedQuery = soQuery;
if (StringUtils.isBlank(selectedQuery)) {
selectedQuery = new StringBuilder()
.append("select ").append(StringUtils.join(selectedFields, ", "))
.append("\n from ").append(soName)
.append("\n where ").append(selectedOrderBy).append(" > {offset}")
.append("\n order by ").append(selectedOrderBy)
.append("\n limit {limit}")
.toString();
}
Map<String, String> partition = new HashMap<>(3);
partition.put(PARTITION_NAME_KEY, soName);
partition.put(PARTITION_ORDER_BY_KEY, selectedOrderBy);
partition.put(PARTITION_QUERY_KEY, selectedQuery.toString());
return Collections.unmodifiableMap(partition);
}
@Override
public Map<String, Object> initialOffset(Map<String, Object> partition) throws APIClientException {
Map<String, Object> offset = new HashMap<>(1);
offset.put(OFFSET_LOG_TIME_KEY, this.initialOffset);
return offset;
}
}
| 43.180905 | 170 | 0.72047 |
6c061e9cacd8a741a2c80dd4191d0d16c7827403 | 2,022 | package game;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.util.ArrayList;
import javax.swing.JFrame;
import game.controllers.BoardGameController;
import game.controllers.MainWindowController;
public final class GameInstance extends JFrame {
private static GameInstance _instance = null;
private final ArrayList<Object> _controllers = new ArrayList<Object>();
private GameInstance() {
super("Tic-Tac-Toe");
setSize(new Dimension(400, 400));
setMaximizedBounds(new Rectangle(getSize()));
setResizable(false);
setMaximumSize(getSize());
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(
(int)screenSize.getWidth() / 2 - getSize().width / 2,
(int)screenSize.getHeight() / 2 - getSize().height / 2
);
}
public void registerController(Object object) {
if(!_controllers.contains(object)) {
_controllers.add(object);
}
}
public Object getController(String type) {
for(Object controller : _controllers) {
String split[] = controller.getClass().getName().split("\\.");
if(split[split.length - 1].equals(type)) {
return controller;
}
}
return null;
}
public static GameInstance getInstance() {
if(_instance == null) {
_instance = new GameInstance();
}
return _instance;
}
public void newGame() {
if(_controllers.size() > 0) {
BoardGameController controller = (BoardGameController)getController("BoardGameController");
controller.reload();
}
else {
// Clears all references to our controller that this
// instance may hold
_controllers.clear();
// Removes any lingering panels without having to worry
// about who owns what
getContentPane().removeAll();
// Create a new controller and start the game
MainWindowController controller = new MainWindowController(getInstance());
registerController(controller);
controller.startGame();
validate();
}
}
} | 25.275 | 94 | 0.6909 |
089d966cd37ed6652fd943a2f6080a8ca4612dcf | 71,398 | /*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.parsepasses.contextautoesc;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Ascii;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.errorprone.annotations.Immutable;
import com.google.template.soy.base.internal.SanitizedContentKind;
import com.google.template.soy.basicdirectives.BlessStringAsTrustedResourceUrlForLegacyDirective;
import com.google.template.soy.soytree.EscapingMode;
import com.google.template.soy.soytree.HtmlAttributeNode;
import com.google.template.soy.soytree.HtmlContext;
import com.google.template.soy.soytree.HtmlTagNode;
import com.google.template.soy.soytree.PrintDirectiveNode;
import com.google.template.soy.soytree.SoyNode;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.regex.Pattern;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
/**
* Encapsulates the context in which a Soy node appears. This helps us distinguish Soy nodes that
* can only be preceded by fully formed HTML tags and text chunks from ones that appear inside
* JavaScript, from ones that appear inside URIs, etc.
*
* <p>This is an immutable bit-packable struct that contains a number of enums. These enums have
* their own nullish values like {@link Context.ElementType#NONE} so should always be non-null.
*
* <p>The contextual autoescape rewriter propagates contexts so that it can infer an appropriate
* {@link EscapingMode escaping function} for each <code>{print ...}</code> command.
*
* <p>To make sure it can correctly identify a unique escape convention for all paths to a
* particular print command, it may clone a template for each context in which it is called, using
* the {@link Context#packedBits bitpacked} form of the context to generate a unique template name.
*
*/
@Immutable
public final class Context {
/**
* List of link types (values of the <link rel=...> attribute) for which the link is a regular
* URL, and not a trusted resource URL. Most of these values are described at
* https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types
*/
private static final ImmutableSet<String> REGULAR_LINK_REL_VALUES =
ImmutableSet.of(
"alternate",
"amphtml",
"apple-touch-icon",
"apple-touch-icon-precomposed",
"apple-touch-startup-image",
"author",
"bookmark",
"canonical",
"cite",
"dns-prefetch",
"help",
"icon",
"license",
"next",
"prefetch",
"preload",
"prerender",
"prev",
"search",
"shortcut",
"subresource",
"tag");
/** Whitespace-separated sequence of regular link types. */
private static final Pattern REGULAR_LINK_PATTERN =
Pattern.compile(
"((^|\\s+)(" + Joiner.on("|").join(REGULAR_LINK_REL_VALUES) + "))*\\s*",
Pattern.CASE_INSENSITIVE);
/** The state the text preceding the context point describes. */
public final HtmlContext state;
/**
* Describes the innermost element that the text preceding the context point is in. An element is
* considered entered once its name has been seen in the start tag and is considered closed once
* the name of its end tag is seen. E.g. the open point is marked with O below and C marks the
* close point.
*
* <pre>{@code
* <b id="boldly-going">Hello, World!</b >
* ^ ^
* O C
* }</pre>
*
* Outside an element, or in PCDATA text, this will be the nullish value {@link ElementType#NONE}.
*/
public final ElementType elType;
/**
* Describes the attribute whose value the context point is in. Outside an attribute value, this
* will be the nullish value {@link AttributeType#NONE}.
*/
public final AttributeType attrType;
/**
* Describes the quoting convention for the attribute value that the context point is in. Outside
* an attribute value, this will be the nullish value {@link AttributeEndDelimiter#NONE}.
*/
public final AttributeEndDelimiter delimType;
/**
* Determines what we will do with a slash token {@code /}. This is irrelevant outside JavaScript
* contexts, but inside JavaScript, it helps us distinguish the contexts of <code>{$bar}</code> in
* <code>"foo".replace(/{$bar}/i)</code> and <code>x/{$bar}/i</code>
*/
public final JsFollowingSlash slashType;
/** Determines how we encode interpolations in URI attributes and CSS {@code uri(...)}. */
public final UriPart uriPart;
/** Determines the context in which this URI is being used. */
public final UriType uriType;
/** Determines position in the HTML attribute value containing HTML. */
public final HtmlHtmlAttributePosition htmlHtmlAttributePosition;
/** The count of {@code <template>} elements entered and not subsequently exited. */
public final int templateNestDepth;
/** The count of {@code js template} elements entered and not subsequently exited. */
public final int jsTemplateLiteralNestDepth;
/** Use {@link Builder} to construct instances. */
private Context(
HtmlContext state,
ElementType elType,
AttributeType attrType,
AttributeEndDelimiter delimType,
JsFollowingSlash slashType,
UriPart uriPart,
UriType uriType,
HtmlHtmlAttributePosition htmlHtmlAttributePosition,
int templateNestDepth,
int jsTemplateLiteralNestDepth) {
this.state = state;
this.elType = elType;
this.attrType = attrType;
this.delimType = delimType;
this.slashType = slashType;
this.uriPart = uriPart;
this.uriType = uriType;
// NOTE: The constraint is one-way; once we see the src attribute we may set the UriType before
// we start actually parsing the URI.
Preconditions.checkArgument(
!(uriPart != UriPart.NONE && uriType == UriType.NONE),
"If in a URI, the type of URI must be specified. UriType = %s but UriPart = %s",
uriType,
uriPart);
this.htmlHtmlAttributePosition = htmlHtmlAttributePosition;
this.templateNestDepth = templateNestDepth;
this.jsTemplateLiteralNestDepth = jsTemplateLiteralNestDepth;
}
/** A context in the given state outside any element, attribute, or Javascript content. */
private Context(HtmlContext state) {
this(
state,
ElementType.NONE,
AttributeType.NONE,
AttributeEndDelimiter.NONE,
JsFollowingSlash.NONE,
UriPart.NONE,
UriType.NONE,
HtmlHtmlAttributePosition.NONE,
0,
0);
}
/**
* The normal context for HTML where a less than opens a tag and an ampersand starts an HTML
* entity.
*/
public static final Context HTML_PCDATA = new Context(HtmlContext.HTML_PCDATA);
/** Returns a context that differs only in the state. */
public Context derive(HtmlContext state) {
return state == this.state ? this : toBuilder().withState(state).build();
}
/** Returns a context that differs only in the following slash. */
public Context derive(JsFollowingSlash slashType) {
return slashType == this.slashType ? this : toBuilder().withSlashType(slashType).build();
}
/** Returns a context that differs only in the uri part. */
public Context derive(UriPart uriPart) {
return uriPart == this.uriPart ? this : toBuilder().withUriPart(uriPart).build();
}
/** Returns a context that differs only in the HTML attribute containing HTML position. */
public Context derive(HtmlHtmlAttributePosition htmlHtmlAttributePosition) {
return htmlHtmlAttributePosition == this.htmlHtmlAttributePosition
? this
: toBuilder().withHtmlHtmlAttributePosition(htmlHtmlAttributePosition).build();
}
/** A mutable builder that allows deriving variant contexts. */
Builder toBuilder() {
return new Builder(this);
}
/**
* The context after printing a correctly-escaped dynamic value in this context.
*
* <p>This makes the optimistic assumption that the escaped string is not empty. This can lead to
* correctness behaviors, but the default is to fail closed; for example, printing an empty string
* at UriPart.START switches to MAYBE_VARIABLE_SCHEME, which is designed not to trust the printed
* value anyway. Same in JS -- we might switch to DIV_OP when we should have stayed in REGEX, but
* in the worse case, we'll just produce JavaScript that doesn't compile (which is safe).
*/
public Context getContextAfterDynamicValue() {
// TODO: If the context is JS, perhaps this should return JsFollowingSlash.UNKNOWN. Right now
// we assume that the dynamic value is also an expression, but JsFollowingSlash.UNKNOWN would
// account for things that end in semicolons (since the next slash could be either a regex OR a
// division op).
if (state == HtmlContext.JS) {
switch (slashType) {
case DIV_OP:
case UNKNOWN:
return this;
case REGEX:
return derive(JsFollowingSlash.DIV_OP);
case NONE:
throw new IllegalStateException(slashType.name());
}
} else if (state == HtmlContext.HTML_BEFORE_OPEN_TAG_NAME
|| state == HtmlContext.HTML_BEFORE_CLOSE_TAG_NAME) {
// We assume ElementType.NORMAL, because filterHtmlElementName filters dangerous tag names.
return toBuilder()
.withState(HtmlContext.HTML_TAG_NAME)
.withElType(ElementType.NORMAL)
.build();
} else if (state == HtmlContext.HTML_TAG) {
// To handle a substitution that starts an attribute name <tag {$attrName}=...>
return toBuilder()
.withState(HtmlContext.HTML_ATTRIBUTE_NAME)
.withAttrType(AttributeType.PLAIN_TEXT)
.build();
} else if (uriPart == UriPart.START) {
if (uriType == UriType.TRUSTED_RESOURCE) {
return derive(UriPart.AUTHORITY_OR_PATH);
}
return derive(UriPart.MAYBE_VARIABLE_SCHEME);
}
return this;
}
/**
* Computes the context after an attribute delimiter is seen.
*
* @param elType The type of element whose tag the attribute appears in.
* @param attrType The type of attribute whose value the delimiter starts.
* @param delim The type of delimiter that will mark the end of the attribute value.
* @param templateNestDepth The number of (@code <template>} elements on the open element stack.
* @return A context suitable for the start of the attribute value.
*/
static Context computeContextAfterAttributeDelimiter(
ElementType elType,
AttributeType attrType,
AttributeEndDelimiter delim,
UriType uriType,
int templateNestDepth) {
HtmlContext state;
JsFollowingSlash slash = JsFollowingSlash.NONE;
UriPart uriPart = UriPart.NONE;
switch (attrType) {
case PLAIN_TEXT:
state = HtmlContext.HTML_NORMAL_ATTR_VALUE;
break;
case SCRIPT:
state = HtmlContext.JS;
// Start a JS block in a regex state since
// /foo/.test(str) && doSideEffect();
// which starts with a regular expression literal is a valid and possibly useful program,
// but there is no valid program which starts with a division operator.
slash = JsFollowingSlash.REGEX;
break;
case STYLE:
state = HtmlContext.CSS;
break;
case HTML:
state = HtmlContext.HTML_HTML_ATTR_VALUE;
break;
case META_REFRESH_CONTENT:
state = HtmlContext.HTML_META_REFRESH_CONTENT;
break;
case URI:
state = HtmlContext.URI;
uriPart = UriPart.START;
break;
// NONE is not a valid AttributeType inside an attribute value.
default:
throw new AssertionError("Unexpected attribute type " + attrType);
}
Preconditions.checkArgument(
(uriType != UriType.NONE) == (attrType == AttributeType.URI),
"uriType=%s but attrType=%s",
uriType,
attrType);
return new Context(
state,
elType,
attrType,
delim,
slash,
uriPart,
uriType,
HtmlHtmlAttributePosition.NONE,
templateNestDepth,
0);
}
private static boolean hasBlessStringAsTrustedResourceUrlForLegacyDirective(
List<PrintDirectiveNode> printDirectives) {
for (PrintDirectiveNode directive : printDirectives) {
// If a print directive with the name "|blessStringAsTrustedResourceUrlForLegacy" exists
// we don't want to enforce presence of a trusted resource URL. This is mainly done so as
// not to break the legacy soy files.
if (directive.getName().equals(BlessStringAsTrustedResourceUrlForLegacyDirective.NAME)) {
return true;
}
}
return false;
}
/**
* Returns the escaping mode appropriate for dynamic content inserted in this context.
*
* @return Empty if there is no appropriate escaping convention to use, e.g. for comments which do
* not have escaping conventions.
*/
public ImmutableList<EscapingMode> getEscapingModes(
SoyNode node, List<PrintDirectiveNode> printDirectives) {
EscapingMode escapingMode = state.getEscapingMode();
// Short circuit on the error case first.
if (escapingMode == null) {
throw SoyAutoescapeException.createWithNode(state.getErrorMessage(), node);
}
// Any additional mode that allows the primary escaping mode's output language to be
// embedded in the specific quoting context in which it appears.
EscapingMode extraEscapingMode = null;
// Make sure we're using the right part for a URI context.
switch (uriPart) {
case QUERY:
escapingMode = EscapingMode.ESCAPE_URI;
break;
case START:
// We need to filter substitutions at the start of a URL since they can switch the
// protocol to a code loading protocol like javascript:. We don't want these filters to
// happen when the URL in question is TrustedResourceUrl as we are sure it is not in
// attacker control.
if (escapingMode != EscapingMode.NORMALIZE_URI) {
extraEscapingMode = escapingMode;
}
switch (uriType) {
case MEDIA:
escapingMode = EscapingMode.FILTER_NORMALIZE_MEDIA_URI;
break;
case REFRESH:
escapingMode = EscapingMode.FILTER_NORMALIZE_REFRESH_URI;
break;
case TRUSTED_RESOURCE:
if (hasBlessStringAsTrustedResourceUrlForLegacyDirective(printDirectives)) {
escapingMode = EscapingMode.NORMALIZE_URI;
} else {
escapingMode = EscapingMode.FILTER_TRUSTED_RESOURCE_URI;
}
break;
case NONE:
case NORMAL:
escapingMode = EscapingMode.FILTER_NORMALIZE_URI;
break;
}
break;
case AUTHORITY_OR_PATH:
case FRAGMENT:
if (uriType == UriType.TRUSTED_RESOURCE) {
escapingMode = EscapingMode.ESCAPE_URI;
}
break;
case UNKNOWN:
case UNKNOWN_PRE_FRAGMENT:
// We can't choose an appropriate escaping convention if we're in a URI but don't know which
// part. E.g. in
// <a href="
// {if ...}
// ?foo=
// {else}
// /bar/
// {/else}
// {$baz}">
// Is {$baz} part of a query or part of a path?
// TODO(gboyer): In these unknown states, it might be interesting to indicate what the two
// contexts were.
throw SoyAutoescapeException.createWithNode(
"Cannot determine which part of the URL this dynamic value is in. Most likely, a"
+ " preceding conditional block began a ?query or #fragment, "
+ "but only on one branch.",
node);
case MAYBE_VARIABLE_SCHEME:
// Is $y in the scheme, path, query, or fragment below?
// <a href="{$x}{$y}">
throw SoyAutoescapeException.createWithNode(
"Soy can't prove this URI concatenation has a safe scheme at compile time."
+ " Either combine adjacent print statements (e.g. {$x + $y} instead of {$x}{$y}),"
+ " or introduce disambiguating characters"
+ " (e.g. {$x}/{$y}, {$x}?y={$y}, {$x}&y={$y}, {$x}#{$y})",
node);
case MAYBE_SCHEME:
// Could $x cause a bad scheme, e.g. if it's "script:deleteMyAccount()"?
// <a href="java{$x}">
throw SoyAutoescapeException.createWithNode(
"Soy can't prove this URI has a safe scheme at compile time. Either make sure one of"
+ " ':', '/', '?', or '#' comes before the dynamic value (e.g. foo/{$bar}), or"
+ " move the print statement to the start of the URI to enable runtime validation"
+ " (e.g. href=\"{'foo' + $bar}\" instead of href=\"foo{$bar}\").",
node);
case DANGEROUS_SCHEME:
// After javascript: or other dangerous schemes.
throw SoyAutoescapeException.createWithNode(
"Soy can't properly escape for this URI scheme. For image sources, you can print full"
+ " data and blob URIs directly (e.g. src=\"{$someDataUri}\")."
+ " Otherwise, hardcode the full URI in the template or pass a complete"
+ " SanitizedContent or SafeUrl object.",
node);
case NONE:
case TRUSTED_RESOURCE_URI_END:
break;
}
// Check the quote embedding mode.
switch (delimType) {
case SPACE_OR_TAG_END:
// Also escape any spaces that could prematurely end the attribute value.
// E.g. when the value of $s is "was checked" in
// <input value={$s}>
// then we want to emit
// <input name=was checked>
// instead of
// <input name=was checked>
if (escapingMode == EscapingMode.ESCAPE_HTML_ATTRIBUTE
|| escapingMode == EscapingMode.NORMALIZE_URI) {
escapingMode = EscapingMode.ESCAPE_HTML_ATTRIBUTE_NOSPACE;
} else {
extraEscapingMode = EscapingMode.ESCAPE_HTML_ATTRIBUTE_NOSPACE;
}
break;
case SINGLE_QUOTE:
case DOUBLE_QUOTE:
if (escapingMode == EscapingMode.NORMALIZE_URI) {
// URI's should still be HTML-escaped to escape ampersands, quotes, and other characters.
// Normalizing a URI (which mostly percent-encodes quotes) is unnecessary if it's going
// to be escaped as an HTML attribute, so as a performance optimization, we simply
// replace the escaper.
escapingMode = EscapingMode.ESCAPE_HTML_ATTRIBUTE;
} else if (!escapingMode.isHtmlEmbeddable) {
// Some modes, like JS and CSS value modes, might insert quotes to make
// a quoted string, so make sure to escape those as HTML.
// E.g. when the value of $s is “' onmouseover=evil() foo='”, in
// <a onclick='alert({$s})'>
// we want to produce
// <a onclick='alert(' onmouseover=evil() foo=')'>
// instead of
// <a onclick='alert(' onmouseover=evil() foo=')'>
extraEscapingMode = EscapingMode.ESCAPE_HTML_ATTRIBUTE;
}
break;
case NONE:
break;
}
// Return and immutable list of (escapingMode, extraEscapingMode)
ImmutableList.Builder<EscapingMode> escapingListBuilder = new ImmutableList.Builder<>();
escapingListBuilder.add(escapingMode);
if (extraEscapingMode != null) {
escapingListBuilder.add(extraEscapingMode);
}
return escapingListBuilder.build();
}
/** Policy for how to handle escaping of a translatable message. */
static final class MsgEscapingStrategy {
/**
* The context in which to parse the message itself. This affects how print nodes are escaped.
*/
final Context childContext;
/**
* The escaping directives for the entire message after all print nodes have been substituted.
*/
final ImmutableList<EscapingMode> escapingModesForFullMessage;
MsgEscapingStrategy(
Context childContext, ImmutableList<EscapingMode> escapingModesForFullMessage) {
this.childContext = childContext;
this.escapingModesForFullMessage = escapingModesForFullMessage;
}
}
/**
* Determines the strategy to escape Soy msg tags.
*
* <p>Importantly, this determines the context that the message should be considered in, how the
* print nodes will be escaped, and how the entire message will be escaped. We need different
* strategies in different contexts because messages in general aren't trusted, but we also need
* to be able to include markup interspersed in an HTML message; for example, an anchor that Soy
* factored out of the message.
*
* <p>Note that it'd be very nice to be able to simply escape the strings that came out of the
* translation database, and distribute the escaping entirely over the print nodes. However, the
* translation machinery, especially in Javascript, doesn't offer a way to escape just the bits
* that come from the translation database without also re-escaping the substitutions.
*
* @param node The node, for error messages
* @return relevant strategy, or absent in case there's no valid strategy and it is an error to
* have a message in this context
*/
Optional<MsgEscapingStrategy> getMsgEscapingStrategy(SoyNode node) {
switch (state) {
case HTML_PCDATA:
// In normal HTML PCDATA context, it makes sense to escape all of the print nodes, but not
// escape the entire message. This allows Soy to support putting anchors and other small
// bits of HTML in messages.
return Optional.of(new MsgEscapingStrategy(this, ImmutableList.of()));
case CSS_DQ_STRING:
case CSS_SQ_STRING:
case JS_DQ_STRING:
case JS_SQ_STRING:
case TEXT:
case URI:
if (state == HtmlContext.URI && uriPart != UriPart.QUERY) {
// NOTE: Only support the query portion of URIs.
return Optional.absent();
}
// In other contexts like JS and CSS strings, it makes sense to treat the message's
// placeholders as plain text, but escape the entire result of message evaluation.
return Optional.of(
new MsgEscapingStrategy(
new Context(HtmlContext.TEXT), getEscapingModes(node, ImmutableList.of())));
case HTML_RCDATA:
case HTML_NORMAL_ATTR_VALUE:
case HTML_COMMENT:
// The weirdest case is HTML attributes. Ideally, we'd like to treat these as a text string
// and escape when done. However, many messages have HTML entities such as » in them.
// A good way around this is to escape the print nodes in the message, but normalize
// (escape except for ampersands) the final message.
// Also, content inside <title>, <textarea>, and HTML comments have a similar requirement,
// where any entities in the messages are probably intended to be preserved.
return Optional.of(
new MsgEscapingStrategy(this, ImmutableList.of(EscapingMode.NORMALIZE_HTML)));
default:
// Other contexts, primarily source code contexts, don't have a meaningful way to support
// natural language text.
return Optional.absent();
}
}
/** True if the given escaping mode could make sense in this context. */
public boolean isCompatibleWith(EscapingMode mode) {
// TODO: Come up with a compatibility matrix.
if (mode == EscapingMode.ESCAPE_JS_VALUE) {
// Don't introduce quotes inside a string.
switch (state) {
case JS_SQ_STRING:
case JS_DQ_STRING:
case CSS_SQ_STRING:
case CSS_DQ_STRING:
return false;
default:
return true;
}
} else if (mode == EscapingMode.TEXT) {
// The TEXT directive may only be used in TEXT mode; in any other context, it would act as
// autoescape-cancelling.
return state == HtmlContext.TEXT;
} else if (delimType == AttributeEndDelimiter.SPACE_OR_TAG_END) {
// Need ESCAPE_HTML_ATTRIBUTE_NOSPACE instead.
if (mode == EscapingMode.ESCAPE_HTML
|| mode == EscapingMode.ESCAPE_HTML_ATTRIBUTE
|| mode == EscapingMode.ESCAPE_HTML_RCDATA) {
return false;
}
}
return true;
}
/**
* Checks if two states are completely identical.
*
* <p>Note it's better to compare either states, or use predicates like isValidEndContext.
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof Context)) {
return false;
}
Context that = (Context) o;
return this.state == that.state
&& this.elType == that.elType
&& this.attrType == that.attrType
&& this.delimType == that.delimType
&& this.slashType == that.slashType
&& this.uriPart == that.uriPart
&& this.uriType == that.uriType
&& this.templateNestDepth == that.templateNestDepth
&& this.jsTemplateLiteralNestDepth == that.jsTemplateLiteralNestDepth;
}
@Override
public int hashCode() {
return packedBits();
}
/**
* An integer form that uniquely identifies this context. This form is not guaranteed to be stable
* across versions, so do not use as a long-lived serialized form.
*/
public int packedBits() {
int bits = templateNestDepth;
bits = (bits << N_URI_TYPE_BITS) | uriType.ordinal();
bits = (bits << N_URI_PART_BITS) | uriPart.ordinal();
bits = (bits << N_JS_SLASH_BITS) | slashType.ordinal();
bits = (bits << N_DELIM_BITS) | delimType.ordinal();
bits = (bits << N_ATTR_BITS) | attrType.ordinal();
bits = (bits << N_ELEMENT_BITS) | elType.ordinal();
bits = (bits << N_STATE_BITS) | state.ordinal();
return bits;
}
/** The number of bits needed to store a {@link HtmlContext} value. */
private static final int N_STATE_BITS = 5;
/** The number of bits needed to store a {@link ElementType} value. */
private static final int N_ELEMENT_BITS = 4;
/** The number of bits needed to store a {@link AttributeType} value. */
private static final int N_ATTR_BITS = 3;
/** The number of bits needed to store a {@link AttributeEndDelimiter} value. */
private static final int N_DELIM_BITS = 2;
/** The number of bits needed to store a {@link JsFollowingSlash} value. */
private static final int N_JS_SLASH_BITS = 2;
/** The number of bits needed to store a {@link UriPart} value. */
private static final int N_URI_PART_BITS = 4;
/** The number of bits needed to store a {@link UriType} value. */
private static final int N_URI_TYPE_BITS = 3;
static {
// extracted to another method to scope the unused suppression, which warns about the dead
// condition (the point is that it is dead)
checkEnoughBits();
}
@SuppressWarnings("unused")
private static void checkEnoughBits() {
// We'd better have enough bits in an int.
if ((N_STATE_BITS
+ N_ELEMENT_BITS
+ N_ATTR_BITS
+ N_DELIM_BITS
+ N_JS_SLASH_BITS
+ N_URI_PART_BITS
+ N_URI_TYPE_BITS)
> 32) {
throw new AssertionError();
}
// And each enum's ordinals must fit in the bits allocated.
if ((1 << N_STATE_BITS) < HtmlContext.values().length
|| (1 << N_ELEMENT_BITS) < ElementType.values().length
|| (1 << N_ATTR_BITS) < AttributeType.values().length
|| (1 << N_DELIM_BITS) < AttributeEndDelimiter.values().length
|| (1 << N_JS_SLASH_BITS) < JsFollowingSlash.values().length
|| (1 << N_URI_PART_BITS) < UriPart.values().length
|| (1 << N_URI_TYPE_BITS) < UriType.values().length) {
throw new AssertionError();
}
}
/** Determines the correct URI part if two branches are joined. */
private static UriPart unionUriParts(UriPart a, UriPart b) {
Preconditions.checkArgument(a != b);
if (a == UriPart.DANGEROUS_SCHEME || b == UriPart.DANGEROUS_SCHEME) {
// Dangerous schemes (like javascript:) are poison -- if either side is dangerous, the whole
// thing is.
return UriPart.DANGEROUS_SCHEME;
} else if (a == UriPart.FRAGMENT
|| b == UriPart.FRAGMENT
|| a == UriPart.UNKNOWN
|| b == UriPart.UNKNOWN) {
// UNKNOWN means one part is in the #fragment and one is not. This is the case if one is
// FRAGMENT and the other is not, or if one of the branches was UNKNOWN to begin with.
return UriPart.UNKNOWN;
} else if ((a == UriPart.MAYBE_VARIABLE_SCHEME || b == UriPart.MAYBE_VARIABLE_SCHEME)
&& a != UriPart.UNKNOWN_PRE_FRAGMENT
&& b != UriPart.UNKNOWN_PRE_FRAGMENT) {
// This is the case you might see on a URL that starts with a print statement, and one
// branch has a slash or ampersand but the other doesn't. Re-entering
// MAYBE_VARIABLE_SCHEME allows us to pretend that the last branch was just part of the
// leading print statement, which leaves us in a relatively-unknown state, but no more
// unknown had it just been completely opaque.
//
// Good Example 1: {$urlWithQuery}{if $a}&a={$a}{/if}{if $b}&b={$b}{/if}
// In this example, the first "if" statement has two branches:
// - "true": {$urlWithQuery}&a={$a} looks like a QUERY due to hueristics
// - "false": {$urlWithQuery} only, which Soy doesn't know at compile-time to actually
// have a query, and it remains in MAYBE_VARIABLE_SCHEME.
// Instead of yielding UNKNOWN, this yields MAYBE_VARIABLE_SCHEME, which the second
// {if $b} can safely deal with.
//
// Good Example 2: {$base}{if $a}/a{/if}{if $b}/b{/if}
// In this, one branch transitions definitely into an authority or path, but the other
// might not. However, we can remain in MAYBE_VARIABLE_SCHEME safely.
return UriPart.MAYBE_VARIABLE_SCHEME;
} else {
// The part is unknown, but we think it's before the fragment. In this case, it's clearly
// ambiguous at compile-time that it's not clear what to do. Examples:
//
// /foo/{if $cond}?a={/if}
// {$base}{if $cond}?a={$a}{else}/b{/if}
// {if $cond}{$base}{else}/a{if $cond2}?b=1{/if}{/if}
//
// Unlike MAYBE_VARIABLE_SCHEME, we don't need to try to gracefully recover here, because
// the template author can easily disambiguate this.
return UriPart.UNKNOWN_PRE_FRAGMENT;
}
}
/**
* A context which is consistent with both contexts. This should be used when multiple execution
* paths join, such as the path through the then-clause of an <code>{if}</code> command and the
* path through the else-clause.
*
* @return Optional.absent() when there is no such context consistent with both.
*/
static Optional<Context> union(Context a, Context b) {
// NOTE: Avoid the temptation to return early; instead, rely on the equals() check at the end
// to ensure all properties match. Checking equals() at the end ensures that when new
// properties are added, they get checked automatically.
// Try to reconcile each property one-by-one.
if (a.slashType != b.slashType) {
a = a.derive(JsFollowingSlash.UNKNOWN);
b = b.derive(JsFollowingSlash.UNKNOWN);
}
if (a.uriPart != b.uriPart) {
UriPart unionedUriPart = unionUriParts(a.uriPart, b.uriPart);
a = a.derive(unionedUriPart);
b = b.derive(unionedUriPart);
}
if (a.state != b.state) {
// Order by state so that we don't have to duplicate tests below.
if (a.state.compareTo(b.state) > 0) {
Context swap = a;
a = b;
b = swap;
}
// consider <div foo=bar{if $p} onclick=foo(){/if} x=y>
// if both branches need a space or tag end to complete, and their states aren't compatible
// switch to TAG_NAME to require a space
if (a.delimType == AttributeEndDelimiter.SPACE_OR_TAG_END
&& b.delimType == AttributeEndDelimiter.SPACE_OR_TAG_END
&& a.state != b.state) {
// we need to switch to a state that requires a space
// TODO(lukes): given this usecase, HTML_TAG_NAME is poorly named, consider
// AFTER_TAG_OR_UNQUOTED_ATTR? maybe just HTML_TAG_NEEDS_SPACE
a = a.toBuilder().withState(HtmlContext.HTML_TAG_NAME).withoutAttrContext().build();
// The next block will clean up b.
}
// consider <input{if $foo} disabled{/if}> or <input{$if foo} disabled=true{/if}
// if we start in a tag name and end in an attribute name or value, assume we are still in a
// tag name.
if (a.state == HtmlContext.HTML_TAG_NAME) {
if (b.state == HtmlContext.HTML_ATTRIBUTE_NAME
|| b.delimType == AttributeEndDelimiter.SPACE_OR_TAG_END) {
// clear attributes from a also, this is counterintuitive because tagnames shouldn't have
// attrccontext at all, but prior reconciliation of slashtype may have added one. so
// clear it.
a = a.toBuilder().withoutAttrContext().build();
b = b.toBuilder().withState(HtmlContext.HTML_TAG_NAME).withoutAttrContext().build();
}
}
// If we start in a tag name and end between attributes, then treat us as between attributes.
// This handles <b{if $bool} attrName="value"{/if}>.
if (a.state == HtmlContext.HTML_TAG_NAME && b.state == HtmlContext.HTML_TAG) {
// Note we only change the state; if the element type is different, we don't want it to
// join.
// TODO(gboyer): The withoutAttrContext() doesn't make any sense, since HTML_TAG_NAME can't
// have an attribute context.
a = a.toBuilder().withState(HtmlContext.HTML_TAG).withoutAttrContext().build();
}
if (a.state == HtmlContext.HTML_TAG) {
// If one branch is waiting for an attribute name, and the other is waiting for an equal
// sign before an attribute value OR the end of an unquoted attribute value, then commit to
// the view that the attribute name was a valueless attribute and transition to a state
// waiting for another attribute name or the end of a tag.
// Examples:
// - state == HTML_ATTRIBUTE_NAME: <input {if $x}disabled{/if}
// - delimType == SPACE_TAG_OR_END: <input {if $x}type=text{/if}
if (b.state == HtmlContext.HTML_ATTRIBUTE_NAME
|| b.delimType == AttributeEndDelimiter.SPACE_OR_TAG_END) {
// TODO(gboyer): do we need to require a space before any new attribute name after an
// unquoted attribute?
b = b.toBuilder().withState(HtmlContext.HTML_TAG).withoutAttrContext().build();
}
}
}
return a.equals(b) ? Optional.of(a) : Optional.absent();
}
static Optional<Context> union(Iterable<Context> contexts) {
Iterator<Context> iterator = contexts.iterator();
Optional<Context> context = Optional.of(iterator.next());
while (iterator.hasNext() && context.isPresent()) {
context = union(context.get(), iterator.next());
}
return context;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("(Context ").append(state.name());
if (elType != ElementType.NONE) {
sb.append(' ').append(elType.name());
}
if (attrType != AttributeType.NONE) {
sb.append(' ').append(attrType.name());
}
if (delimType != AttributeEndDelimiter.NONE) {
sb.append(' ').append(delimType.name());
}
if (slashType != JsFollowingSlash.NONE) {
sb.append(' ').append(slashType.name());
}
if (uriPart != UriPart.NONE) {
sb.append(' ').append(uriPart.name());
}
if (uriType != UriType.NONE) {
sb.append(' ').append(uriType.name());
}
if (templateNestDepth != 0) {
sb.append(" templateNestDepth=").append(templateNestDepth);
}
if (jsTemplateLiteralNestDepth != 0) {
sb.append(" jsTemplateLiteralNestDepth=").append(jsTemplateLiteralNestDepth);
}
return sb.append(')').toString();
}
/** Parses a condensed string version of a context, for use in tests. */
@VisibleForTesting
static Context parse(String text) {
Queue<String> parts = Lists.newLinkedList(Arrays.asList(text.split(" ")));
Context.Builder builder = HTML_PCDATA.toBuilder();
builder.withState(HtmlContext.valueOf(parts.remove()));
if (!parts.isEmpty()) {
try {
builder.withElType(ElementType.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withAttrType(AttributeType.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withDelimType(AttributeEndDelimiter.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withSlashType(JsFollowingSlash.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withUriPart(UriPart.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
try {
builder.withUriType(UriType.valueOf(parts.element()));
parts.remove();
} catch (IllegalArgumentException ex) {
// OK
}
}
if (!parts.isEmpty()) {
String part = parts.element();
String prefix = "templateNestDepth=";
if (part.startsWith(prefix)) {
try {
builder.withTemplateNestDepth(Integer.parseInt(part.substring(prefix.length())));
parts.remove();
} catch (NumberFormatException ex) {
// OK
}
}
}
if (!parts.isEmpty()) {
String part = parts.element();
String prefix = "jsTemplateLiteralNestDepth=";
if (part.startsWith(prefix)) {
try {
builder.withJsTemplateLiteralNestDepth(Integer.parseInt(part.substring(prefix.length())));
parts.remove();
} catch (NumberFormatException ex) {
// OK
}
}
}
if (!parts.isEmpty()) {
throw new IllegalArgumentException(
"Unable to parse context \"" + text + "\". Unparsed portion: " + parts);
}
Context result = builder.build();
return result;
}
/**
* Returns the autoescape {@link Context} that produces sanitized content of the given {@link
* SanitizedContentKind}.
*
* <p>Given a {@link SanitizedContentKind}, returns the corresponding {@link Context} such that
* contextual autoescaping of a block of Soy code with that context as the start context results
* in a value that adheres to the contract of {@link
* com.google.template.soy.data.SanitizedContent} of the given kind.
*/
public static Context getStartContextForContentKind(SanitizedContentKind contentKind) {
return HTML_PCDATA.toBuilder().withStartKind(contentKind).build();
}
/**
* Determines whether a particular context is valid at the start of a block of a particular
* content kind.
*/
public boolean isValidStartContextForContentKind(SanitizedContentKind contentKind) {
if (templateNestDepth != 0) {
return false;
}
switch (contentKind) {
case ATTRIBUTES:
// Allow HTML attribute names, regardless of the kind of attribute (e.g. plain text)
// or immediately after an open tag.
return state == HtmlContext.HTML_ATTRIBUTE_NAME || state == HtmlContext.HTML_TAG;
default:
// NOTE: For URI's, we need to be picky that the context has no attribute type, since we
// don't want to forget to escape ampersands.
return this.equals(getStartContextForContentKind(contentKind));
}
}
/**
* Determines whether a particular context is allowed for contextual to strict calls.
*
* <p>This is slightly more relaxed, and used to help piecemeal transition of templates from
* contextual to strict.
*/
public boolean isValidStartContextForContentKindLoose(SanitizedContentKind contentKind) {
switch (contentKind) {
case URI:
// Allow contextual templates directly call URI templates, even if we technically need to
// do HTML-escaping for correct output. Supported browsers recover gracefully when
// ampersands are underescaped, as long as there are no nearby semicolons. However, this
// special case is limited ONLY to transitional cases, where the caller is contextual and
// the callee is strict.
return state == HtmlContext.URI;
default:
return isValidStartContextForContentKind(contentKind);
}
}
private static final ImmutableMap<HtmlContext, SanitizedContentKind> STATE_TO_CONTENT_KIND;
static {
Map<HtmlContext, SanitizedContentKind> stateToContextKind = new EnumMap<>(HtmlContext.class);
stateToContextKind.put(HtmlContext.CSS, SanitizedContentKind.CSS);
stateToContextKind.put(HtmlContext.HTML_PCDATA, SanitizedContentKind.HTML);
stateToContextKind.put(HtmlContext.HTML_TAG, SanitizedContentKind.ATTRIBUTES);
stateToContextKind.put(HtmlContext.JS, SanitizedContentKind.JS);
stateToContextKind.put(HtmlContext.URI, SanitizedContentKind.URI);
stateToContextKind.put(HtmlContext.TEXT, SanitizedContentKind.TEXT);
STATE_TO_CONTENT_KIND = ImmutableMap.copyOf(stateToContextKind);
}
/**
* Returns the most sensible content kind for a context.
*
* <p>This is primarily for error messages, indicating to the user what content kind can be used
* to mostly null out the escaping. Returns TEXT if no useful match was detected.
*/
public SanitizedContentKind getMostAppropriateContentKind() {
SanitizedContentKind kind = STATE_TO_CONTENT_KIND.get(state);
if (kind != null && isValidStartContextForContentKindLoose(kind)) {
return kind;
}
return SanitizedContentKind.TEXT;
}
/**
* Determines whether a particular context is valid for the end of a block of a particular content
* kind.
*/
public final boolean isValidEndContextForContentKind(SanitizedContentKind contentKind) {
if (templateNestDepth != 0) {
return false;
}
switch (contentKind) {
case CSS:
return state == HtmlContext.CSS && elType == ElementType.NONE;
case HTML:
return state == HtmlContext.HTML_PCDATA && elType == ElementType.NONE;
case ATTRIBUTES:
// Allow any html attribute context or html tag this. HTML_TAG is needed for constructs
// like "checked" that don't require an attribute value. Explicitly disallow
// HTML_NORMAL_ATTR_VALUE (e.g. foo={$x} without quotes) to help catch cases where
// attributes aren't safely composable (e.g. foo={$x}checked would end up with one long
// attribute value, whereas foo="{$x}"checked would be parsed as intended).
return state == HtmlContext.HTML_ATTRIBUTE_NAME || state == HtmlContext.HTML_TAG;
case JS:
// Just ensure the state is JS -- don't worry about whether a regex is coming or not.
return state == HtmlContext.JS && elType == ElementType.NONE;
case URI:
// Ensure that the URI content is non-empty and the URI type remains normal (which is
// the assumed type of the URI content kind).
return state == HtmlContext.URI && uriType == UriType.NORMAL && uriPart != UriPart.START;
case TEXT:
return state == HtmlContext.TEXT;
case TRUSTED_RESOURCE_URI:
// Ensure that the URI content is non-empty and the URI type remains normal (which is
// the assumed type of the URI content kind).
return state == HtmlContext.URI
&& uriType == UriType.TRUSTED_RESOURCE
&& uriPart != UriPart.START;
}
throw new IllegalArgumentException(
"Specified content kind " + contentKind + " has no associated end context.");
}
/**
* Returns a plausible human-readable description of a context mismatch;
*
* <p>This assumes that the provided context is an invalid end context for the particular content
* kind.
*/
public final String getLikelyEndContextMismatchCause(SanitizedContentKind contentKind) {
Preconditions.checkArgument(!isValidEndContextForContentKind(contentKind));
if (contentKind == SanitizedContentKind.ATTRIBUTES) {
// Special error message for ATTRIBUTES since it has some specific logic.
return "an unterminated attribute value, or ending with an unquoted attribute";
}
switch (state) {
case HTML_TAG_NAME:
case HTML_TAG:
case HTML_ATTRIBUTE_NAME:
case HTML_NORMAL_ATTR_VALUE:
return "an unterminated HTML tag or attribute";
case CSS:
return "an unclosed style block or attribute";
case JS:
case JS_LINE_COMMENT: // Line comments are terminated by end of input.
return "an unclosed script block or attribute";
case CSS_COMMENT:
case HTML_COMMENT:
case JS_BLOCK_COMMENT:
return "an unterminated comment";
case CSS_DQ_STRING:
case CSS_SQ_STRING:
case JS_DQ_STRING:
case JS_SQ_STRING:
return "an unterminated string literal";
case URI:
case CSS_URI:
case CSS_DQ_URI:
case CSS_SQ_URI:
return "an unterminated or empty URI";
case JS_REGEX:
return "an unterminated regular expression";
default:
if (templateNestDepth != 0) {
return "an unterminated <template> element";
} else {
return "unknown to compiler";
}
}
}
/** Returns a new context in the given {@link HtmlContext state}. */
@CheckReturnValue
Context transitionToState(HtmlContext state) {
Context.Builder builder = toBuilder().withState(state).withUriPart(UriPart.NONE);
if (uriPart != UriPart.NONE) {
// Only reset the URI type if we're leaving a URI; intentionally, URI type needs to
// remain prior to the URI, for example, to maintain state between "src", the "=", and
// the opening quotes (if any).
builder.withUriType(UriType.NONE);
}
return builder.build();
}
/**
* Returns a new context given the tag name.
*
* <p>This mostly handles special context changing tags like {@code <script>}.
*
* @param node The name of the tag
*/
@CheckReturnValue
Context transitionToTagName(HtmlTagNode node) {
// according to spec ascii case is not meaningful for tag names.
String tagName = node.getTagName().getStaticTagNameAsLowerCase();
boolean isEndTag = state == HtmlContext.HTML_BEFORE_CLOSE_TAG_NAME;
Context.ElementType elType = ElementType.NORMAL;
int newTemplateNestDepth = templateNestDepth;
if (tagName.equals("template")) {
newTemplateNestDepth += isEndTag ? -1 : 1;
if (newTemplateNestDepth < 0) {
throw SoyAutoescapeException.createWithNode(
"Saw an html5 </template> without encountering <template>.", node);
}
} else if (!isEndTag) {
// We currently only treat <img> and SVG's <image> as a media type, since for <video> and
// <audio> there are concerns that attackers could introduce rich video or audio that
// facilitates social engineering. Upon further review, it's possible we may allow them.
switch (tagName) {
case "img":
case "image":
elType = ElementType.MEDIA;
break;
case "iframe":
elType = ElementType.IFRAME;
break;
case "script":
elType = ElementType.SCRIPT;
break;
case "style":
elType = ElementType.STYLE;
break;
case "base":
elType = ElementType.BASE;
break;
case "link":
if (node.getDirectAttributeNamed("rel") == null
&& node.getDirectAttributeNamed("itemprop") != null) {
elType = ElementType.NORMAL;
} else {
String rel = getStaticAttributeValue(node, "rel");
elType =
rel != null && REGULAR_LINK_PATTERN.matcher(rel).matches()
? ElementType.NORMAL
: ElementType.LINK_EXECUTABLE;
}
break;
case "meta":
String httpEquiv = getStaticAttributeValue(node, "http-equiv");
elType =
"refresh".equalsIgnoreCase(httpEquiv) ? ElementType.META_REFRESH : ElementType.NORMAL;
break;
case "textarea":
elType = ElementType.TEXTAREA;
break;
case "title":
elType = ElementType.TITLE;
break;
case "xmp":
elType = ElementType.XMP;
break;
default: // fall out
}
}
return toBuilder()
.withState(HtmlContext.HTML_TAG_NAME)
.withoutAttrContext()
.withElType(elType)
.withTemplateNestDepth(newTemplateNestDepth)
.build();
}
private String getStaticAttributeValue(HtmlTagNode node, String name) {
HtmlAttributeNode attribute = node.getDirectAttributeNamed(name);
return attribute == null ? null : attribute.getStaticContent();
}
/** Returns a new context that is in {@link HtmlContext#HTML_TAG}. */
@CheckReturnValue
Context transitionToTagBody() {
return toBuilder().withState(HtmlContext.HTML_TAG).withoutAttrContext().build();
}
/** Returns a new context in whatever state is appropriate given the current {@code elType}. */
@CheckReturnValue
Context transitionToAfterTag() {
Context.Builder builder = toBuilder();
builder.withoutAttrContext();
switch (elType) {
case SCRIPT:
builder
.withState(HtmlContext.JS)
.withSlashType(Context.JsFollowingSlash.REGEX)
.withElType(Context.ElementType.NONE);
break;
case STYLE:
builder.withState(HtmlContext.CSS).withElType(Context.ElementType.NONE);
break;
case TEXTAREA:
case TITLE:
case XMP:
builder.withState(HtmlContext.HTML_RCDATA);
break;
// All normal or void tags fit here.
case NORMAL:
case BASE:
case LINK_EXECUTABLE:
case META_REFRESH:
case IFRAME:
case MEDIA:
builder.withState(HtmlContext.HTML_PCDATA).withElType(Context.ElementType.NONE);
break;
case NONE:
throw new IllegalStateException();
}
return builder.build();
}
/**
* Lower case names of attributes whose value is a URI. This does not identify attributes like
* {@code <meta content>} which is conditionally a URI depending on the value of other attributes.
*
* @see <a href="http://www.w3.org/TR/html4/index/attributes.html">HTML4 attrs with type %URI</a>
*/
private static final ImmutableSet<String> URI_ATTR_NAMES =
ImmutableSet.of(
"action",
"archive",
"base",
"background",
"cite",
"classid",
"codebase",
/**
* TODO: content is only a URL sometimes depending on other parameters and existing
* templates use content with non-URL values. Fix those templates or otherwise flag
* interpolations into content.
*/
// "content",
"data",
"dsync",
"formaction",
"href",
"icon",
"longdesc",
"manifest",
"poster",
"src",
"usemap",
// Custom attributes that are reliably URLs in existing code.
"entity");
/** Matches lower-case attribute local names that start or end with "url" or "uri". */
private static final Pattern CUSTOM_URI_ATTR_NAMING_CONVENTION =
Pattern.compile("\\bur[il]|ur[il]s?$");
/** Returns a new context based on the attribute name and current element type. */
@CheckReturnValue
Context transitionToAttrName(String attrName) {
// according to spec ascii case is not meaningful for attributes.
attrName = Ascii.toLowerCase(attrName);
// Get the local name so we can treat xlink:href and svg:style as per HTML.
int colon = attrName.lastIndexOf(':');
String localName = attrName.substring(colon + 1);
Context.AttributeType attr;
UriType uriType = UriType.NONE;
if (localName.startsWith("on")) {
attr = Context.AttributeType.SCRIPT;
} else if ("ng-init".equals(attrName)) {
// ng-init is an attribute used in the AngularJS framework. According to its documentation,
// "There are only a few appropriate uses of ngInit, such as [...] injecting data via server
// side scripting" (https://docs.angularjs.org/api/ng/directive/ngInit). Soy supports this by
// ensuring that interpolating server side data inside the ng-init attribute will not lead to
// Angular expression injection vulnerabilities (https://docs.angularjs.org/guide/security).
//
// The content of the attribute follows an expression syntax very similar to JavaScript. In
// fact, the syntax is a subset of JS, though the bitwise OR operator has different semantics
// (piping into a filter function). Because of this, treating the attribute as JS in Soy will
// ensure that the injected data will always be interpreted as a primitive data type by
// Angular and won't be parsed as an expression (similarly to how Soy prevents JS injection
// in on* attributes). See the documentation for details on the syntax:
// https://docs.angularjs.org/guide/expression#angularjs-expressions-vs-javascript-expressions
//
// The set of places where Angular tries to find and interpret expressions in the DOM depends
// on its interpolation rules (https://docs.angularjs.org/guide/interpolation) and directives
// (https://docs.angularjs.org/guide/directive). Since
// - each application can define additional directives
// - directives can be triggered by HTML comments, element names, attributes (not just ng-
// attributes) and a special CSS class syntax
// - the interpolation start and end symbols can be changed
// it is not feasible to cover all cases in Soy. Instead, we rely on the fact that all
// templates can be refactored to use ng-init for passing the server side data. In other
// words, Soy enables safely passing data, but it doesn't (and can't) force it.
attr = Context.AttributeType.SCRIPT;
} else if ("style".equals(localName)) {
attr = Context.AttributeType.STYLE;
} else if (elType == Context.ElementType.MEDIA
&& ("src".equals(attrName) || "xlink:href".equals(attrName))) {
attr = Context.AttributeType.URI;
uriType = UriType.MEDIA;
} else if ((elType == ElementType.SCRIPT && "src".equals(attrName))
|| (elType == ElementType.IFRAME && "src".equals(attrName))
|| (elType == ElementType.LINK_EXECUTABLE && "href".equals(attrName))
|| (elType == ElementType.BASE && "href".equals(attrName))) {
attr = Context.AttributeType.URI;
uriType = UriType.TRUSTED_RESOURCE;
} else if (URI_ATTR_NAMES.contains(localName)
|| CUSTOM_URI_ATTR_NAMING_CONVENTION.matcher(localName).find()
|| "xmlns".equals(attrName)
|| attrName.startsWith("xmlns:")) {
attr = Context.AttributeType.URI;
uriType = UriType.NORMAL;
} else if (elType == ElementType.META_REFRESH && "content".equals(attrName)) {
attr = AttributeType.META_REFRESH_CONTENT;
} else if (elType == ElementType.IFRAME && "srcdoc".equals(attrName)) {
attr = Context.AttributeType.HTML;
} else {
attr = Context.AttributeType.PLAIN_TEXT;
}
return toBuilder()
.withState(HtmlContext.HTML_ATTRIBUTE_NAME)
.withoutAttrContext()
.withAttrType(attr)
.withUriType(uriType)
.build();
}
/** Returns a new context that is in attribute value using the given attribute delimiter. */
@CheckReturnValue
Context transitionToAttrValue(AttributeEndDelimiter delim) {
// TODO(lukes): inline this method?
return computeContextAfterAttributeDelimiter(
elType, attrType, delim, uriType, templateNestDepth);
}
/** A type of HTML element. */
public enum ElementType {
/** No element. */
NONE,
/** A script element whose content is raw JavaScript. */
SCRIPT,
/** A style element whose content is raw CSS. */
STYLE,
/** A base element, so that we can process the href attribute specially. */
BASE,
/** A textarea element whose content is encoded HTML but which cannot contain elements. */
TEXTAREA,
/** A title element whose content is encoded HTML but which cannot contain elements. */
TITLE,
/** An XMP element whose content is raw CDATA. */
XMP,
/** An image element, so that we can process the src attribute specially. */
MEDIA,
/** An iframe element, so that we can process the src attribute specially. */
IFRAME,
/**
* An executable link element, e.g. with rel="stylesheet" or rel="import" or with unknown rel,
* so that we can process the href attribute specially.
*/
LINK_EXECUTABLE,
/** A {@code <meta http-equiv="refresh">} element. */
META_REFRESH,
/** An element whose content is normal mixed PCDATA and child elements. */
NORMAL,
;
}
/** Describes the content of an HTML attribute. */
public enum AttributeType {
/** No attribute. */
NONE,
/** Mime-type text/javascript. */
SCRIPT,
/** Mime-type text/css. */
STYLE,
/** Mime-type text/html. */
HTML,
/** A URI or URI reference. */
URI,
/** The value of content attribute in {@code <meta http-equiv="refresh">}. */
META_REFRESH_CONTENT,
/** Other content. Human readable or other non-structured plain text or keyword values. */
PLAIN_TEXT,
;
}
/** Describes the content that will end the current HTML attribute. */
public enum AttributeEndDelimiter {
/** Not in an attribute. */
NONE,
/** {@code "} */
DOUBLE_QUOTE("\""),
/** {@code '} */
SINGLE_QUOTE("'"),
/** A space or {@code >} symbol. */
SPACE_OR_TAG_END(""),
;
/**
* The suffix of the attribute that is not part of the attribute value. E.g. in {@code
* href="foo"} the trailing double quote is part of the attribute but not part of the value.
* Whereas for space delimited attributes like {@code width=32}, there is no non-empty suffix
* that is part of the attribute but not part of the value.
*/
public final @Nullable String text;
AttributeEndDelimiter(String text) {
this.text = text;
}
AttributeEndDelimiter() {
this.text = null;
}
}
/**
* Describes what a slash ({@code /}) means when parsing JavaScript source code. A slash that is
* not followed by another slash or an asterisk (<tt>*</tt>) can either start a regular expression
* literal or start a division operator. This determination is made based on the full grammar, but
* Waldemar defined a very close to accurate grammar for a JavaScript 1.9 draft based purely on a
* regular lexical grammar which is what we use in the autoescaper.
*
* @see JsUtil#isRegexPreceder
*/
public enum JsFollowingSlash {
/** Not in JavaScript. */
NONE,
/** A slash as the next token would start a regular expression literal. */
REGEX,
/** A slash as the next token would start a division operator. */
DIV_OP,
/**
* We do not know what a slash as the next token would start so it is an error for the next
* token to be a slash.
*/
UNKNOWN,
;
}
/**
* Describes the part of a URI reference that the context point is in.
*
* <p>We need to distinguish these so that we can
*
* <ul>
* <li>normalize well-formed URIs that appear before the query,
* <li>encode raw values interpolated as query parameters or keys,
* <li>filter out values that specify a scheme like {@code javascript:}.
* </ul>
*/
public enum UriPart {
/** Not in a URI. */
NONE,
/**
* At the absolute beginning of a URI.
*
* <p>At ^ in {@code ^http://host/path?k=v#frag} or {@code ^foo/bar?a=1}.
*/
START,
/**
* This is used for static TRUSTED_RESOURCE_URIs with no print nodes. We throw an error if
* there's a print node in this state.
*/
TRUSTED_RESOURCE_URI_END,
/**
* After a print statement in the beginning of a URI, where it's still possible to be in the
* scheme.
*
* <p>For example, after {@code href="{$x}}, it's hard to know what will happen.
* For example, if $x is "java" (a perfectly valid relative URI on its own), then
* "script:alert(1)" would execute as Javascript. But if $x is "java" followed by "/test.html",
* it's a relative URI.
*
* <p>This state is kept until we see anything that's hard-coded that makes it clear that we've
* left the scheme context; while remaining in this state, print statements and colons are
* forbidden, since we don't want what looks like a relative URI to set the scheme.
*/
MAYBE_VARIABLE_SCHEME,
/**
* Still possibly in the scheme, though it could also be a relative path, but no print
* statements have been seen yet.
*
* <p>For example, between carets in {@code h^ttp^://host/path} or {@code f^oo^/bar.html}.
*
* <p>This is similar to MAYBE_VARIABLE_SCHEME in that print statements are forbidden; however,
* colons are allowed and transition to AUTHORITY_OR_PATH.
*/
MAYBE_SCHEME,
/**
* In the scheme, authority, or path. Between ^s in {@code h^ttp://host/path^?k=v#frag}.
*
* <p>In the specific case of {@link UriType#TRUSTED_RESOURCE}, this must be a part of the path.
*/
AUTHORITY_OR_PATH,
/** In the query portion. Between ^s in {@code http://host/path?^k=v^#frag} */
QUERY,
/** In the fragment. After ^ in {@code http://host/path?k=v#^frag} */
FRAGMENT,
/** Not {@link #NONE} or {@link #FRAGMENT}, but unknown. Used to join different contexts. */
UNKNOWN_PRE_FRAGMENT,
/** Not {@link #NONE}, but unknown. Used to join different contexts. */
UNKNOWN,
/** A known-dangerous scheme where dynamic content is forbidden. */
DANGEROUS_SCHEME;
}
/**
* Describes the type or context of a URI that is currently being or about to be parsed.
*
* <p>This distinguishes between the types of URI safety concerns, which vary between images,
* scripts, and other types.
*/
public enum UriType {
/**
* Not in or about to be in a URI.
*
* <p>Note the URI type can be set even if we haven't entered the URI itself yet.
*/
NONE,
/**
* General URI context suitable for most URI types.
*
* <p>The biggest use-case here is for anchors, where we want to prevent Javascript URLs that
* can cause XSS. However, this grabs other types of URIs such as prefetch, SEO metadata, and
* attributes that look like they're supposed to contain URIs but might just be harmless
* metadata because they end with "url".
*
* <p>It's expected that this will be split up over time to address the different safety levels
* of the different URI types.
*/
NORMAL,
/**
* Image URL type.
*
* <p>Here, we can relax some some rules. For example, a data URI in an image is unlikely to do
* anything that loading an image from a 3rd party http/https site.
*
* <p>At present, note that Soy doesn't do anything to prevent referer[r]er leakage. At some
* future point, we may want to provide configuration options to avoid 3rd party or
* http-in-the-clear image loading.
*
* <p>In the future, this might also encompass video and audio, if we can find ways to reduce
* the risk of social engineering.
*/
MEDIA,
/**
* URL used in {@code <meta http-equiv="Refresh" content="0; URL=">}.
*
* <p>Compared to the normal URL, ';' is escaped because it is a special character in this
* context.
*/
REFRESH,
/**
* A URI which loads resources. This is intended to be used in scripts, stylesheets, etc which
* should not be in attacker control.
*
* <ul>
* <li>Constant strings are allowed
* <li>If the uri has a fixed scheme+host+path, then we can allow the remaining parts to be
* interpolated as long as they are percent encoded.
* <li>If the prefix is dynamic then we require it to be a trusted_resource_uri.
* </ul>
*/
TRUSTED_RESOURCE;
}
/** Describes position in HTML attribute value containing HTML (e.g. {@code <iframe srcdoc>}). */
public enum HtmlHtmlAttributePosition {
/** Not in HTML attribute value containing HTML or at its start. */
NONE,
/** Inside HTML attribute value containing HTML but not at the start. */
NOT_START;
}
/** A mutable builder for {@link Context}s. */
static final class Builder {
private HtmlContext state;
private ElementType elType;
private AttributeType attrType;
private AttributeEndDelimiter delimType;
private JsFollowingSlash slashType;
private UriPart uriPart;
private UriType uriType;
private HtmlHtmlAttributePosition htmlHtmlAttributePosition;
private int templateNestDepth;
private int jsTemplateLiteralNestDepth;
private Builder(Context context) {
this.state = context.state;
this.elType = context.elType;
this.attrType = context.attrType;
this.delimType = context.delimType;
this.slashType = context.slashType;
this.uriPart = context.uriPart;
this.uriType = context.uriType;
this.htmlHtmlAttributePosition = context.htmlHtmlAttributePosition;
this.templateNestDepth = context.templateNestDepth;
this.jsTemplateLiteralNestDepth = context.jsTemplateLiteralNestDepth;
}
Builder withState(HtmlContext state) {
this.state = Preconditions.checkNotNull(state);
return this;
}
Builder withElType(ElementType elType) {
this.elType = Preconditions.checkNotNull(elType);
return this;
}
Builder withAttrType(AttributeType attrType) {
this.attrType = Preconditions.checkNotNull(attrType);
return this;
}
Builder withDelimType(AttributeEndDelimiter delimType) {
this.delimType = Preconditions.checkNotNull(delimType);
return this;
}
Builder withSlashType(JsFollowingSlash slashType) {
this.slashType = Preconditions.checkNotNull(slashType);
return this;
}
Builder withUriPart(UriPart uriPart) {
this.uriPart = Preconditions.checkNotNull(uriPart);
return this;
}
Builder withUriType(UriType uriType) {
this.uriType = Preconditions.checkNotNull(uriType);
return this;
}
Builder withHtmlHtmlAttributePosition(HtmlHtmlAttributePosition htmlHtmlAttributePosition) {
this.htmlHtmlAttributePosition = Preconditions.checkNotNull(htmlHtmlAttributePosition);
return this;
}
Builder withTemplateNestDepth(int templateNestDepth) {
checkArgument(
templateNestDepth >= 0, "expected template depth (%s) to be >= 0", templateNestDepth);
this.templateNestDepth = templateNestDepth;
return this;
}
Builder withJsTemplateLiteralNestDepth(int jsTemplateLiteralNestDepth) {
checkArgument(
jsTemplateLiteralNestDepth >= 0,
"expected js template string nest depth (%s) to be >= 0",
jsTemplateLiteralNestDepth);
this.jsTemplateLiteralNestDepth = jsTemplateLiteralNestDepth;
return this;
}
Builder withoutAttrContext() {
return this.withAttrType(Context.AttributeType.NONE)
.withDelimType(Context.AttributeEndDelimiter.NONE)
.withSlashType(Context.JsFollowingSlash.NONE)
.withUriPart(Context.UriPart.NONE)
.withUriType(Context.UriType.NONE);
}
/**
* Reset to a {@link Context} such that contextual autoescaping of a block of Soy code with the
* corresponding {@link SanitizedContentKind} results in a value that adheres to the contract of
* {@link com.google.template.soy.data.SanitizedContent} of this kind.
*/
Builder withStartKind(SanitizedContentKind contentKind) {
boolean inTag = false;
withoutAttrContext();
switch (contentKind) {
case CSS:
withState(HtmlContext.CSS);
break;
case HTML:
withState(HtmlContext.HTML_PCDATA);
break;
case ATTRIBUTES:
withState(HtmlContext.HTML_TAG);
inTag = true;
break;
case JS:
withState(HtmlContext.JS);
withSlashType(JsFollowingSlash.REGEX);
break;
case URI:
withState(HtmlContext.URI);
withUriPart(UriPart.START);
// Assume a let block of kind="uri" is a "normal" URI.
withUriType(UriType.NORMAL);
break;
case TEXT:
withState(HtmlContext.TEXT);
break;
case TRUSTED_RESOURCE_URI:
withState(HtmlContext.URI);
withUriPart(UriPart.START);
withUriType(UriType.TRUSTED_RESOURCE);
break;
}
if (!inTag) {
withElType(ElementType.NONE);
}
return this;
}
Context build() {
return new Context(
state,
elType,
attrType,
delimType,
slashType,
uriPart,
uriType,
htmlHtmlAttributePosition,
templateNestDepth,
jsTemplateLiteralNestDepth);
}
}
}
| 38.635281 | 100 | 0.654612 |
bb5f16b5be624e3447ba5a9f8f26c2b8b9c702c6 | 156 | package io.leopard.web.mvc.json;
/**
* 图片地址转换器
*
* @author 谭海潮
*
*/
public interface ImageUrlConverter {
String convert(String uri);
}
| 12 | 37 | 0.615385 |
6722d584f09cb3ead9448c98a72fcedc13c50a5a | 728 | package com.dataflow.demo.templates.util;
public class FileUtil {
private FileUtil() {
throw new IllegalStateException("Utility class");
}
public static String getFileName(String fileNameUrl) {
return fileNameUrl.substring(fileNameUrl.lastIndexOf("/") + 1);
}
public static String getBucketName(String fileNameUrl) {
String bucketName;
if (fileNameUrl.contains("//")) {
bucketName = fileNameUrl.substring(fileNameUrl.lastIndexOf("//") + 2);
} else {
bucketName = fileNameUrl;
}
if (bucketName.contains("/")) {
return bucketName.substring(0, bucketName.indexOf("/"));
}
return bucketName;
}
}
| 28 | 82 | 0.614011 |
443ee2524d752129534e867057c3ab697a03043c | 5,203 | /*
* Copyright (c) 2019-2021 TagnumElite
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.tagnumelite.projecteintegration.addons;
import appeng.api.features.InscriberProcessType;
import appeng.recipes.handlers.GrinderRecipe;
import appeng.recipes.handlers.InscriberRecipe;
import com.tagnumelite.projecteintegration.api.conversion.AConversionProvider;
import com.tagnumelite.projecteintegration.api.conversion.ConversionProvider;
import com.tagnumelite.projecteintegration.api.recipe.ARecipeTypeMapper;
import moze_intel.projecte.api.data.CustomConversionBuilder;
import moze_intel.projecte.api.mapper.recipe.RecipeTypeMapper;
import moze_intel.projecte.emc.mappers.recipe.BaseRecipeTypeMapper;
import net.minecraft.item.Item;
import net.minecraft.item.Items;
import net.minecraft.item.crafting.IRecipeType;
import net.minecraft.item.crafting.Ingredient;
import net.minecraftforge.common.Tags;
import net.minecraftforge.registries.ObjectHolder;
import java.util.Collections;
import java.util.List;
public class AppliedEnergisticsAddon {
public static final String MODID = "appliedenergistics2";
@RecipeTypeMapper(requiredMods = MODID, priority = 1)
public static class AEGrinderMapper extends BaseRecipeTypeMapper {
@Override
public String getName() {
return "AppliedEnergisticsGrinderMapper";
}
@Override
public String getDescription() {
return "Recipe mapper for Applied Energistics grinder. NOTE: Optional outputs are ignored";
}
@Override
public boolean canHandle(IRecipeType<?> iRecipeType) {
return iRecipeType == GrinderRecipe.TYPE;
}
}
@RecipeTypeMapper(requiredMods = MODID, priority = 1)
public static class AEInscriberMapper extends ARecipeTypeMapper<InscriberRecipe> {
@Override
public String getName() {
return "AppliedEnergisticsInscriberMapper";
}
@Override
public String getDescription() {
return "Recipe mapper for Applied Energistics inscriber";
}
@Override
public boolean canHandle(IRecipeType<?> iRecipeType) {
return iRecipeType == InscriberRecipe.TYPE;
}
@Override
protected List<Ingredient> getIngredients(InscriberRecipe recipe) {
// Whoops, forgot that inscribing exists.
if (recipe.getProcessType() == InscriberProcessType.INSCRIBE) {
return Collections.singletonList(recipe.getMiddleInput());
}
return super.getIngredients(recipe);
}
}
@ConversionProvider(MODID)
@ObjectHolder("appliedenergistics2")
public static class AEConversionProvider extends AConversionProvider {
@ObjectHolder("certus_quartz_crystal")
public static final Item CERTUS_QUARTZ_CRYSTAL = null;
@ObjectHolder("charged_certus_quartz_crystal")
public static final Item CERTUS_QUARTZ_CRYSTAL_CHARGED = null;
@ObjectHolder("fluix_crystal")
public static final Item FLUIX_CRYSTAL = null;
@ObjectHolder("nether_quartz_seed")
public static final Item NETHER_QUARTZ_SEED = null;
@ObjectHolder("fluix_crystal_seed")
public static final Item FLUIX_CRYSTAL_SEED = null;
@ObjectHolder("certus_crystal_seed")
public static final Item CERTUS_CRYSTAL_SEED = null;
@Override
public void convert(CustomConversionBuilder builder) {
builder.comment("Set defaults conversions for Applied Energistics")
.before(CERTUS_QUARTZ_CRYSTAL, 256)
.conversion(CERTUS_QUARTZ_CRYSTAL_CHARGED).ingredient(CERTUS_QUARTZ_CRYSTAL).end()
.conversion(FLUIX_CRYSTAL, 2).ingredient(CERTUS_QUARTZ_CRYSTAL_CHARGED).ingredient(Tags.Items.DUSTS_REDSTONE).ingredient(Items.QUARTZ).end()
.conversion(Items.QUARTZ).ingredient(NETHER_QUARTZ_SEED).end()
.conversion(FLUIX_CRYSTAL).ingredient(FLUIX_CRYSTAL_SEED).end()
.conversion(CERTUS_QUARTZ_CRYSTAL).ingredient(CERTUS_CRYSTAL_SEED).end();
}
}
}
| 43 | 160 | 0.721891 |
99e5b06fae40581f9e45a9e79f09a5a8c414c368 | 1,255 | package aQute.service.reporter;
import java.util.*;
/**
* A base interface to represent the state of a work in progress.
*/
public interface Report {
/**
* Defines a record for the location of an error/warning
*/
class Location {
public String message;
public int line;
public String file;
public String header;
public String context;
public String reference;
public String methodName;
/**
* @see SetLocation#details(Object)
*/
public Object details;
public int length;
}
/**
* Return the warnings. This list must not be changed and may be
* immutable. @return the warnings
*/
List<String> getWarnings();
/**
* Return the errors. This list must not be changed and may be
* immutable. @return the errors
*/
List<String> getErrors();
/**
* Return the errors for the given error or warning. Can return null. @param
* msg The message @return null or the location of the message
*/
Location getLocation(String msg);
/**
* Check if this report has any relevant errors that should make the run
* associated with this report invalid. I.e. if this returns false then the
* run should be disregarded. @return true if this run should be disregarded
* due to errors
*/
boolean isOk();
}
| 23.240741 | 77 | 0.697211 |
971cbd0498f562d265baf2c59e7502cdec89bb4f | 1,477 | package softuni.OOP.encapsulation.PizzaCalories;
import java.util.ArrayList;
import java.util.List;
public class Pizza {
private String name;
private Dough dough;
private List<Topping> toppings;
public
Pizza (String name, int numberOfToppings) {
this.setName (name);
this.setToppings (numberOfToppings);
}
private
void setName (String name) {
if (name == null || name.trim ().isEmpty () || name.length () > 15) {
throw new IllegalArgumentException ("Pizza name should be between 1 and 15 symbols.");
}
this.name = name;
}
private
void setToppings (int numberOfToppings) {
if (numberOfToppings < 0 || numberOfToppings > 10) {
throw new IllegalArgumentException ("Number of toppings should be in range [0..10].");
}
this.toppings = new ArrayList<> (numberOfToppings);
}
public
void setDough (Dough dough) {
this.dough = dough;
}
public
String getName () {
return this.name;
}
public
void addTopping (Topping topping) {
this.toppings.add (topping);
}
public
double getOverallCalories () {
return this.dough.calculateCalories () + this.toppings.stream ().mapToDouble (Topping::calculateCalories).sum ();
}
@Override
public
String toString () {
return String.format ("%s - %.2f", this.getName (), this.getOverallCalories ());
}
}
| 24.213115 | 121 | 0.614083 |
e7449ccf04e4fd89058ed13871740de6f3da5df2 | 376 | package org.squiddev.plethora.core.wrapper;
final class BadWrapperException extends RuntimeException {
public static final BadWrapperException INSTANCE = new BadWrapperException("Error generating method wrapper");
private static final long serialVersionUID = -1429222867771289808L;
private BadWrapperException(String message) {
super(message, null, true, false);
}
}
| 31.333333 | 111 | 0.81117 |
c4f8d880532fdc60a8aa4a34edffc2d2ad683dd2 | 7,137 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.cubic.agent.remote;
import com.cubic.agent.conf.AgentConfig;
import com.cubic.agent.process.Processor;
import com.cubic.serialization.agent.v1.CommonMessage;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author luqiang
*/
public class AgentNettyClient {
private static final Logger log = LoggerFactory.getLogger(AgentNettyClient.class);
private final Bootstrap bootstrap = new Bootstrap();
private final EventLoopGroup WORKER_GROUP = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() - 1, new ThreadFactoryBuilder().setNameFormat("oap-netty-server-worker").build());
private final AtomicBoolean running = new AtomicBoolean(false);
private final SettableFuture<Void> started = SettableFuture.create();
private volatile Channel channel;
private final List<String> tcpServers;
private final Random random = new Random();
private List<Processor> processors;
public AgentNettyClient() {
tcpServers = Arrays.asList(AgentConfig.Agent.TCP_SERVERS.split(","));
}
public void init(List<Processor> processors) {
this.processors = processors;
log.info("AgentNettyClient init process size:{}", processors.size());
}
public void start() {
final IdleStateHandler idleStateHandler = new IdleStateHandler(0, 0, 2, TimeUnit.MINUTES);
final AgentRequestHandler requestHandler = new AgentRequestHandler(processors);
final ConnectionManagerHandler connectionManagerHandler = new ConnectionManagerHandler();
int index = Math.abs(random.nextInt()) % tcpServers.size();
String server = tcpServers.get(index);
String[] ipAndPort = server.split(":");
bootstrap.group(WORKER_GROUP)
.channel(NioSocketChannel.class)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.SO_REUSEADDR, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) {
socketChannel.pipeline()
.addLast(new ProtobufVarint32FrameDecoder())
.addLast(new ProtobufDecoder(CommonMessage.getDefaultInstance()))
.addLast(new ProtobufVarint32LengthFieldPrepender())
.addLast(new ProtobufEncoder())
.addLast(idleStateHandler)
.addLast(requestHandler)
.addLast(connectionManagerHandler);
}
});
log.info("will connection server:{}...", server);
bootstrap.connect(ipAndPort[0], Integer.parseInt(ipAndPort[1])).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
log.info("cubic netty client start success");
channel = future.channel();
running.compareAndSet(false, true);
started.set(null);
} else {
started.set(null);
}
});
try {
started.get();
} catch (InterruptedException e) {
log.error("start cubic netty client error", e);
Thread.currentThread().interrupt();
} catch (Exception e) {
log.error("start cubic netty client error", e);
}
}
public boolean isRunning() {
return running.get();
}
public Channel getChannel() {
return this.channel;
}
@ChannelHandler.Sharable
private class ConnectionManagerHandler extends ChannelDuplexHandler {
@Override
public void disconnect(ChannelHandlerContext ctx, ChannelPromise future) throws Exception {
log.warn("agent netty client channel disconnect, {}", ctx.channel());
destroyAndSync();
super.disconnect(ctx, future);
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
log.info("agent netty client channel active, {}", ctx.channel());
super.channelActive(ctx);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
log.warn("agent netty client channel inactive, {}", ctx.channel());
destroyAndSync();
//如果运行过程中服务端挂了,执行重连机制
super.channelInactive(ctx);
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
log.warn("agent netty client idle, {}", ctx.channel());
destroyAndSync();
} else {
super.userEventTriggered(ctx, evt);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
destroyAndSync();
}
}
public synchronized void destroyAndSync() {
if (running.compareAndSet(true, false)) {
log.warn("agent netty client destroy, {}", channel);
try {
channel.close().syncUninterruptibly();
} catch (Exception e) {
log.error("close channel error", e);
}
}
}
}
| 36.6 | 195 | 0.649152 |
5245eb1f11a56581d8f5ca14c8e0c337360b3f8e | 2,745 | /*******************************************************************************
* Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source
* Project (AJOSP) Contributors and others.
*
* SPDX-License-Identifier: Apache-2.0
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution, and is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Open Connectivity Foundation and Contributors to AllSeen
* Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*******************************************************************************/
package com.at4wireless.alljoyn.localagent.view.common;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ViewCommons
{
private static final Logger logger = LogManager.getLogger(ViewCommons.class.getName());
public static Rectangle setCenteredRectangle(int rectangleWidth, int rectangleHeight)
{
Dimension screenDimensions = Toolkit.getDefaultToolkit().getScreenSize();
int xCenter = (screenDimensions.width - rectangleWidth)/2;
int yCenter = (screenDimensions.height - rectangleHeight)/2;
return new Rectangle(xCenter, yCenter, rectangleWidth, rectangleHeight);
}
public static Image readImageFromFile(String imagePath, String imageName)
{
Image image = null;
try
{
image = ImageIO.read(new File(imagePath + File.separator + imageName));
}
catch (IOException e)
{
logger.warn(String.format("Resource %s not found", imageName));
}
return image;
}
} | 38.661972 | 90 | 0.664845 |
37796593cf4a0a520ddee5fa69df6facb214ddf0 | 1,616 | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.plugin.core.navigation.locationreferences;
import ghidra.program.model.address.Address;
import ghidra.program.model.listing.Program;
import ghidra.program.util.ProgramLocation;
import ghidra.program.util.VariableXRefFieldLocation;
import ghidra.util.exception.AssertException;
public class VariableXRefLocationDescriptor extends XRefLocationDescriptor {
VariableXRefLocationDescriptor(ProgramLocation location, Program program) {
super(location, program);
}
@Override
protected void validate() {
if (programLocation == null) {
throw new NullPointerException(
"Cannot create a LocationDescriptor from a null " + "ProgramLocation");
}
if (!(programLocation instanceof VariableXRefFieldLocation)) {
throw new AssertException("Unexpected ProgramLocation type - Cannot create a " +
"LocationDescriptor for type: " + programLocation);
}
}
@Override
protected Address getXRefAddress(ProgramLocation location) {
return ((VariableXRefFieldLocation) location).getRefAddress();
}
}
| 33.666667 | 83 | 0.767327 |
5e6b3d777c215664d1cb5292b9a122cc690f58e2 | 1,635 | /*
* 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.examproject.service;
import java.util.HashMap;
import java.util.Map;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.examproject.repository.OrderRepository;
/**
* @author h.adachi
*/
@Slf4j
@RequiredArgsConstructor
@Service("inventoryService")
public class InventoryServiceImpl implements InventoryService {
///////////////////////////////////////////////////////////////////////////
// Fields
@NonNull
private final OrderRepository orderRepository;
///////////////////////////////////////////////////////////////////////////
// public Methods
@Override
public Map<String, Long> getOrderCountMap() {
Map<String, Long> countNameMap = new HashMap<>();
orderRepository.sumQuantityGroupByProductName().stream().map(o -> (Object[]) o)
.forEachOrdered((array) -> {
countNameMap.put((String) array[1], (Long) array[0]);
});
return countNameMap;
}
}
| 29.727273 | 87 | 0.643425 |
3e0a31407be836cc60cc1b76f45969a6aa71e5aa | 1,657 | package pl.karoldabrowski.newsapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class ArticleAdapter extends ArrayAdapter<Article> {
public ArticleAdapter(@NonNull Context context, List<Article> articles) {
super(context, 0, articles);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Article currentArticle = getItem(position);
TextView articleTitle = listItemView.findViewById(R.id.article_title);
articleTitle.setText(currentArticle.getTitle());
if(currentArticle.hasAuthor()) {
TextView articleAuthor = listItemView.findViewById(R.id.article_author);
articleAuthor.setText(currentArticle.getAuthor());
}
TextView articleSection = listItemView.findViewById(R.id.article_section);
articleSection.setText(currentArticle.getSection());
if(currentArticle.hasDate()) {
TextView articleDate = listItemView.findViewById(R.id.article_date);
articleDate.setText(currentArticle.getDate().replace('T', ' ').replace("Z", ""));
}
return listItemView;
}
}
| 33.14 | 94 | 0.697043 |
987e06cbdd7a988b73723c9ba948a0a899a6b749 | 6,538 | /**
* Copyright (c) 2011, The University of Southampton and the individual contributors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the University of Southampton nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openimaj.image.processing.convolution;
import org.openimaj.image.FImage;
import org.openimaj.image.processor.SinglebandImageProcessor;
import org.openimaj.math.matrix.MatrixUtils;
import Jama.SingularValueDecomposition;
/**
* Base class for implementation of classes that perform convolution operations
* on {@link FImage}s as a @link{SinglebandImageProcessor}, with the kernel
* itself formed from and @link{FImage}.
*
* @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
*/
public class FConvolution implements SinglebandImageProcessor<Float, FImage> {
/** The kernel */
public FImage kernel;
private ConvolveMode mode;
interface ConvolveMode {
public void convolve(FImage f);
class OneD implements ConvolveMode {
private float[] kernel;
private boolean rowMode;
OneD(FImage image) {
if (image.height == 1) {
this.rowMode = true;
this.kernel = image.pixels[0];
}
else {
this.rowMode = false;
this.kernel = new float[image.height];
for (int i = 0; i < image.height; i++)
this.kernel[i] = image.pixels[i][0];
}
}
@Override
public void convolve(FImage f) {
if (this.rowMode)
FImageConvolveSeparable.convolveHorizontal(f, kernel);
else
FImageConvolveSeparable.convolveVertical(f, kernel);
}
}
class Separable implements ConvolveMode {
private float[] row;
private float[] col;
Separable(SingularValueDecomposition svd) {
final int nrows = svd.getU().getRowDimension();
this.row = new float[nrows];
this.col = new float[nrows];
final float factor = (float) Math.sqrt(svd.getS().get(0, 0));
for (int i = 0; i < nrows; i++) {
this.row[i] = (float) svd.getU().get(i, 0) * factor;
this.col[i] = (float) svd.getV().get(i, 0) * factor;
}
}
@Override
public void convolve(FImage f) {
FImageConvolveSeparable.convolveHorizontal(f, row);
FImageConvolveSeparable.convolveVertical(f, col);
}
}
class BruteForce implements ConvolveMode {
protected FImage kernel;
BruteForce(FImage kernel) {
this.kernel = kernel;
}
@Override
public void convolve(FImage image) {
final int kh = kernel.height;
final int kw = kernel.width;
final int hh = kh / 2;
final int hw = kw / 2;
final FImage clone = image.newInstance(image.width, image.height);
for (int y = hh; y < image.height - (kh - hh); y++) {
for (int x = hw; x < image.width - (kw - hw); x++) {
float sum = 0;
for (int j = 0, jj = kh - 1; j < kh; j++, jj--) {
for (int i = 0, ii = kw - 1; i < kw; i++, ii--) {
final int rx = x + i - hw;
final int ry = y + j - hh;
sum += image.pixels[ry][rx] * kernel.pixels[jj][ii];
}
}
clone.pixels[y][x] = sum;
}
}
image.internalAssign(clone);
}
}
}
/**
* Construct the convolution operator with the given kernel
*
* @param kernel
* the kernel
*/
public FConvolution(FImage kernel) {
this.kernel = kernel;
setup(false);
}
/**
* Construct the convolution operator with the given kernel
*
* @param kernel
* the kernel
*/
public FConvolution(float[][] kernel) {
this.kernel = new FImage(kernel);
setup(false);
}
/**
* Set brute-force convolution; disables kernel separation and other
* optimisations.
*
* @param brute
*/
public void setBruteForce(boolean brute) {
setup(brute);
}
private void setup(boolean brute) {
if (brute) {
this.mode = new ConvolveMode.BruteForce(this.kernel);
return;
}
if (this.kernel.width == 1 || this.kernel.height == 1) {
this.mode = new ConvolveMode.OneD(kernel);
}
else {
final SingularValueDecomposition svd = new SingularValueDecomposition(
MatrixUtils.matrixFromFloat(this.kernel.pixels));
if (svd.rank() == 1)
this.mode = new ConvolveMode.Separable(svd);
else
this.mode = new ConvolveMode.BruteForce(this.kernel);
}
}
/*
* (non-Javadoc)
*
* @see
* org.openimaj.image.processor.ImageProcessor#processImage(org.openimaj
* .image.Image)
*/
@Override
public void processImage(FImage image) {
mode.convolve(image);
}
/**
* Return the kernel response at the x,y in the given image.
*
* This method will throw an array index out of bounds if x,y requests
* pixels outside the image bounds
*
* @param x
* @param y
* @param image
* @return the kernel response at the given coordinates
*/
public float responseAt(int x, int y, FImage image) {
float sum = 0;
final int kh = kernel.height;
final int kw = kernel.width;
final int hh = kh / 2;
final int hw = kw / 2;
for (int j = 0, jj = kh - 1; j < kh; j++, jj--) {
for (int i = 0, ii = kw - 1; i < kw; i++, ii--) {
final int rx = x + i - hw;
final int ry = y + j - hh;
sum += image.pixels[ry][rx] * kernel.pixels[jj][ii];
}
}
return sum;
}
}
| 28.30303 | 85 | 0.666106 |
aa81b3df0af530e554c06c84a2ea9ea3fcd13feb | 124 | public class MyClass extends SomeOtherClass {
public void someMethod(String x) {
System.out.println(x);
}
}
| 20.666667 | 45 | 0.669355 |
5bdf366bdbadd3e9b4103cac52ed6d9e56e5d971 | 149 | package com.android.cglib.proxy;
import java.lang.reflect.Method;
public interface MethodFilter {
boolean filter(Method method, String str);
}
| 18.625 | 46 | 0.771812 |
7f875012e0e39a4d7e470651dd04b2bb53280079 | 14,214 | /**
* Copyright 2016 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.jbpm.designer.expressioneditor;
import org.jbpm.designer.expressioneditor.model.Condition;
import org.jbpm.designer.expressioneditor.model.ConditionExpression;
import org.jbpm.designer.expressioneditor.parser.ExpressionScriptGenerator;
import org.jbpm.designer.expressioneditor.server.ExpressionEditorErrors;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class ExpressionScriptGeneratorTest {
private ExpressionScriptGenerator generator = new ExpressionScriptGenerator();
private ConditionExpression expression;
private List<String> errors;
private Condition condition;
private List<String> parameters;
@Before
public void setUp() throws Exception {
expression = new ConditionExpression();
errors = new ArrayList<String>();
expression.setOperator("AND");
expression.setConditions(new ArrayList<Condition>());
condition = new Condition();
parameters = new ArrayList<String>();
}
@Test
public void testEqual() throws Exception {
condition.setFunction(Condition.EQUALS_TO);
parameters.add("variable");
parameters.add("value");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.equalsTo(variable, \"value\");", script);
assertEquals(0, errors.size());
}
@Test
public void testEqualEmptyValue() throws Exception {
condition.setFunction(Condition.EQUALS_TO);
parameters.add("variable");
parameters.add("");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertNull(script);
assertEquals(1, errors.size());
assertEquals(ExpressionEditorErrors.PARAMETER_NULL_EMPTY, errors.get(0));
}
@Test
public void testContains() throws Exception {
condition.setFunction(Condition.CONTAINS);
parameters.add("variable");
parameters.add("value");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.contains(variable, \"value\");", script);
assertEquals(0, errors.size());
}
@Test
public void testContainsEmptyValue() throws Exception {
condition.setFunction(Condition.CONTAINS);
parameters.add("variable");
parameters.add("");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertNull(script);
assertEquals(1, errors.size());
assertEquals(ExpressionEditorErrors.PARAMETER_NULL_EMPTY, errors.get(0));
}
@Test
public void testIsNull() throws Exception {
condition.setFunction(Condition.IS_NULL);
parameters.add("variable");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.isNull(variable);", script);
assertEquals(0, errors.size());
}
@Test
public void testIsEmpty() throws Exception {
condition.setFunction(Condition.IS_EMPTY);
parameters.add("variable");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.isEmpty(variable);", script);
assertEquals(0, errors.size());
}
@Test
public void testStartsWith() throws Exception {
condition.setFunction(Condition.STARTS_WITH);
parameters.add("variable");
parameters.add("value");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.startsWith(variable, \"value\");", script);
assertEquals(0, errors.size());
}
@Test
public void testStartsWithEmptyValue() throws Exception {
condition.setFunction(Condition.STARTS_WITH);
parameters.add("variable");
parameters.add("");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertNull(script);
assertEquals(1, errors.size());
assertEquals(ExpressionEditorErrors.PARAMETER_NULL_EMPTY, errors.get(0));
}
@Test
public void testEndsWith() throws Exception {
condition.setFunction(Condition.ENDS_WITH);
parameters.add("variable");
parameters.add("value");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.endsWith(variable, \"value\");", script);
assertEquals(0, errors.size());
}
@Test
public void testEndsWithEmptyValue() throws Exception {
condition.setFunction(Condition.ENDS_WITH);
parameters.add("variable");
parameters.add("");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertNull(script);
assertEquals(1, errors.size());
assertEquals(ExpressionEditorErrors.PARAMETER_NULL_EMPTY, errors.get(0));
}
@Test
public void testIsTrue() throws Exception {
condition.setFunction(Condition.IS_TRUE);
parameters.add("variable");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.isTrue(variable);", script);
assertEquals(0, errors.size());
}
@Test
public void testIsFalse() throws Exception {
condition.setFunction(Condition.IS_FALSE);
parameters.add("variable");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.isFalse(variable);", script);
assertEquals(0, errors.size());
}
@Test
public void testBetween() throws Exception {
condition.setFunction(Condition.BETWEEN);
parameters.add("variable");
parameters.add("value");
parameters.add("secondValue");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.between(variable, \"value\", \"secondValue\");", script);
assertEquals(0, errors.size());
}
@Test
public void testBetweenEmptyValue() throws Exception {
condition.setFunction(Condition.BETWEEN);
parameters.add("variable");
parameters.add("");
parameters.add("secondValue");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertNull(script);
assertEquals(1, errors.size());
assertEquals(ExpressionEditorErrors.PARAMETER_NULL_EMPTY, errors.get(0));
}
@Test
public void testBetweenEmptySecondValue() throws Exception {
condition.setFunction(Condition.BETWEEN);
parameters.add("variable");
parameters.add("value");
parameters.add("");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertNull(script);
assertEquals(1, errors.size());
assertEquals(ExpressionEditorErrors.PARAMETER_NULL_EMPTY, errors.get(0));
}
@Test
public void testGreaterThan() throws Exception {
condition.setFunction(Condition.GREATER_THAN);
parameters.add("variable");
parameters.add("value");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.greaterThan(variable, \"value\");", script);
assertEquals(0, errors.size());
}
@Test
public void testGreaterThanEmptyValue() throws Exception {
condition.setFunction(Condition.GREATER_THAN);
parameters.add("variable");
parameters.add("");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertNull(script);
assertEquals(1, errors.size());
assertEquals(ExpressionEditorErrors.PARAMETER_NULL_EMPTY, errors.get(0));
}
@Test
public void testLessThan() throws Exception {
condition.setFunction(Condition.LESS_THAN);
parameters.add("variable");
parameters.add("value");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.lessThan(variable, \"value\");", script);
assertEquals(0, errors.size());
}
@Test
public void testLessThanEmptyValue() throws Exception {
condition.setFunction(Condition.LESS_THAN);
parameters.add("variable");
parameters.add("");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertNull(script);
assertEquals(1, errors.size());
assertEquals(ExpressionEditorErrors.PARAMETER_NULL_EMPTY, errors.get(0));
}
@Test
public void testGreaterOrEqualThan() throws Exception {
condition.setFunction(Condition.GREATER_OR_EQUAL_THAN);
parameters.add("variable");
parameters.add("value");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.greaterOrEqualThan(variable, \"value\");", script);
assertEquals(0, errors.size());
}
@Test
public void testGreaterOrEqualThanEmptyValue() throws Exception {
condition.setFunction(Condition.GREATER_OR_EQUAL_THAN);
parameters.add("variable");
parameters.add("");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertNull(script);
assertEquals(1, errors.size());
assertEquals(ExpressionEditorErrors.PARAMETER_NULL_EMPTY, errors.get(0));
}
@Test
public void testLessOrEqualThan() throws Exception {
condition.setFunction(Condition.LESS_OR_EQUAL_THAN);
parameters.add("variable");
parameters.add("value");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.lessOrEqualThan(variable, \"value\");", script);
assertEquals(0, errors.size());
}
@Test
public void testLessOrEqualThanEmptyValue() throws Exception {
condition.setFunction(Condition.LESS_OR_EQUAL_THAN);
parameters.add("variable");
parameters.add("");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertNull(script);
assertEquals(1, errors.size());
assertEquals(ExpressionEditorErrors.PARAMETER_NULL_EMPTY, errors.get(0));
}
@Test
public void testAnd() throws Exception {
condition.setFunction(Condition.GREATER_THAN);
parameters.add("variable");
parameters.add("value");
condition.setParameters(parameters);
expression.getConditions().add(condition);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertEquals("return KieFunctions.greaterThan(variable, \"value\") && KieFunctions.greaterThan(variable, \"value\");", script);
assertEquals(0, errors.size());
}
@Test
public void testInvalidFunction() throws Exception {
condition.setFunction("invalidFunction");
parameters.add("variable");
parameters.add("value");
condition.setParameters(parameters);
expression.getConditions().add(condition);
String script = generator.generateScript(expression, errors);
assertNull(script);
assertEquals(1, errors.size());
assertEquals("Invalid function: invalidFunction", errors.get(0));
}
}
| 39.157025 | 136 | 0.679682 |
4764fedea04963e298d66b1027afe4ba37a5aee2 | 391 | /* Generated by AN DISI Unibo */
package it.unibo.reqconsole;
import it.unibo.qactors.QActorContext;
import it.unibo.is.interfaces.IOutputEnvView;
import it.unibo.qactors.akka.QActorMsgQueue;
public class MsgHandle_Reqconsole extends QActorMsgQueue{
public MsgHandle_Reqconsole(String actorId, QActorContext myCtx, IOutputEnvView outEnvView ) {
super(actorId, myCtx, outEnvView);
}
}
| 32.583333 | 96 | 0.808184 |
142069cc7f52c8e6f35769bfd129671475407688 | 2,157 | package com.jzy.game.cluster.server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jzy.game.cluster.AppCluster;
import com.jzy.game.engine.mina.config.MinaServerConfig;
import com.jzy.game.engine.script.ScriptManager;
import com.jzy.game.engine.thread.ThreadPoolExecutorConfig;
import com.jzy.game.engine.util.SysUtil;
import com.jzy.game.model.constant.NetPort;
/**
* 集群管理服务器
*
* @author JiangZhiYong
* @date 2017-03-31 QQ:359135103
*/
public class ClusterServer implements Runnable {
private static final Logger log = LoggerFactory.getLogger(ClusterServer.class);
private final ClusterHttpServer clusterHttpServer;
private final ClusterTcpServer clusterTcpServer;
public ClusterServer(ThreadPoolExecutorConfig defaultThreadExcutorConfig4HttpServer,
MinaServerConfig minaServerConfig4HttpServer, ThreadPoolExecutorConfig defaultThreadExcutorConfig4TcpServer,
MinaServerConfig minaServerConfig4TcpServer) {
NetPort.CLUSTER_PORT = minaServerConfig4TcpServer.getPort();
NetPort.CLUSTER_HTTP_PORT = minaServerConfig4HttpServer.getHttpPort();
clusterHttpServer = new ClusterHttpServer(defaultThreadExcutorConfig4HttpServer, minaServerConfig4HttpServer);
clusterTcpServer = new ClusterTcpServer(defaultThreadExcutorConfig4TcpServer, minaServerConfig4TcpServer);
}
public static ClusterServer getInstance() {
return AppCluster.getClusterServer();
}
@Override
public void run() {
// mainServerThread.addTimerEvent(new ServerHeartTimer());
// 启动mina相关
log.info("ClusterServer::clusterHttpServer::start!!!");
new Thread(clusterHttpServer).start();
log.info("ClusterServer::clusterTcpServer::start!!!");
new Thread(clusterTcpServer).start();
ScriptManager.getInstance().init((str) -> SysUtil.exit(this.getClass(), null, "加载脚本错误"));
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
log.error("", ex);
}
log.info("---->集群服启动成功<----");
}
public ClusterHttpServer getLoginHttpServer() {
return clusterHttpServer;
}
public ClusterTcpServer getLoginTcpServer() {
return clusterTcpServer;
}
}
| 32.19403 | 113 | 0.765415 |
31bb6f16b2b520d8a3f48203b596b2f72caa8440 | 2,338 | /*
* Copyright (c) 2012, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.jtt.micro;
import org.junit.Test;
import org.graalvm.compiler.jtt.JTTTest;
public class FloatingReads extends JTTTest {
public static long init = Runtime.getRuntime().totalMemory();
private final int f = 10;
private int a;
private int b;
private int c;
public int test(int d) {
a = 3;
b = 5;
c = 7;
for (int i = 0; i < d; i++) {
if (i % 2 == 0) {
a += b;
}
if (i % 4 == 0) {
b += c;
} else if (i % 3 == 0) {
b -= a;
}
if (i % 5 == 0) {
for (int j = 0; j < i; j++) {
c += a;
}
a -= f;
}
b = a ^ c;
if (i % 6 == 0) {
c--;
} else if (i % 7 == 0) {
Runtime.getRuntime().totalMemory();
}
}
return a + b + c;
}
@Test
public void run0() {
runTest("test", 10);
}
@Test
public void run1() {
runTest("test", 1000);
}
@Test
public void run2() {
runTest("test", 1);
}
@Test
public void run3() {
runTest("test", 0);
}
}
| 27.186047 | 79 | 0.543627 |
0fc2487944afc9454a2826151e8b1bcba55d9bfb | 2,157 | /*****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
****************************************************************/
package org.apache.cayenne.remote;
import org.apache.cayenne.testdo.mt.ClientMtTable1;
import org.apache.cayenne.testdo.mt.ClientMtTable2;
/**
* This is a test primarily for CAY-1118
*/
public class RelationshipChangeTest extends RemoteCayenneCase {
public void testNullify() {
ClientMtTable1 o1 = context.newObject(ClientMtTable1.class);
ClientMtTable2 o2 = context.newObject(ClientMtTable2.class);
o2.setTable1(o1);
assertEquals(1, o1.getTable2Array().size());
context.commitChanges();
o2.setTable1(null);
assertEquals(0, o1.getTable2Array().size());
}
public void testChange() {
ClientMtTable1 o1 = context.newObject(ClientMtTable1.class);
ClientMtTable2 o2 = context.newObject(ClientMtTable2.class);
ClientMtTable1 o3 = context.newObject(ClientMtTable1.class);
o2.setTable1(o1);
assertEquals(1, o1.getTable2Array().size());
context.commitChanges();
o2.setTable1(o3);
assertEquals(0, o1.getTable2Array().size());
assertEquals(1, o3.getTable2Array().size());
}
}
| 37.189655 | 69 | 0.633287 |
b6cdae099fb0dc2507a86f4664cfd037703b3a9d | 2,707 | package com.smart.sso.server.session.redis;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smart.sso.server.common.AccessTokenContent;
import com.smart.sso.server.session.AccessTokenManager;
/**
* 分布式调用凭证管理
*
* @author Joe
*/
@Component
@ConditionalOnProperty(name = "sso.session.manager", havingValue = "redis")
public class RedisAccessTokenManager implements AccessTokenManager {
@Value("${sso.timeout}")
private int timeout;
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public void create(String accessToken, AccessTokenContent accessTokenContent) {
redisTemplate.opsForValue().set(accessToken, JSON.toJSONString(accessTokenContent), getExpiresIn(),
TimeUnit.SECONDS);
redisTemplate.opsForSet().add(getKey(accessTokenContent.getCodeContent().getTgt()), accessToken);
}
@Override
public AccessTokenContent get(String accessToken) {
String atcStr = redisTemplate.opsForValue().get(accessToken);
if (StringUtils.isEmpty(atcStr)) {
return null;
}
return JSONObject.parseObject(atcStr, AccessTokenContent.class);
}
@Override
public boolean refresh(String accessToken) {
if (redisTemplate.opsForValue().get(accessToken) == null) {
return false;
}
redisTemplate.expire(accessToken, timeout, TimeUnit.SECONDS);
return true;
}
@Override
public void remove(String tgt) {
Set<String> accessTokenSet = redisTemplate.opsForSet().members(getKey(tgt));
if (CollectionUtils.isEmpty(accessTokenSet)) {
return;
}
redisTemplate.delete(getKey(tgt));
accessTokenSet.forEach(accessToken -> {
String atcStr = redisTemplate.opsForValue().get(accessToken);
if (StringUtils.isEmpty(atcStr)) {
return;
}
AccessTokenContent accessTokenContent = JSONObject.parseObject(atcStr, AccessTokenContent.class);
if (accessTokenContent == null || !accessTokenContent.getCodeContent().isSendLogoutRequest()) {
return;
}
sendLogoutRequest(accessTokenContent.getCodeContent().getRedirectUri(), accessToken);
});
}
private String getKey(String tgt) {
return tgt + "_access_token";
}
/**
* accessToken时效为登录session时效的1/2
*/
@Override
public int getExpiresIn() {
return timeout / 2;
}
}
| 29.423913 | 101 | 0.768748 |
9e35786dbe9b3666125e617a44bb004b2e120bb1 | 770 | package com.stocks_analyzer.commons.util;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Logger;
/**
* Class関する付属情報を提供します。
*
* @author chotto-martini
* @since 1.0.0
*/
public class ClassUtils {
/** Logger定義 */
private static Logger LOGGER = (Logger) LoggerFactory.getLogger(ClassUtils.class.getName());
/**
* このメソッドを参照しているメソッド名を返します。
*
* @return このメソッドを参照しているメソッド名を返します。
*
* @author chotto-martini
* @since 1.0.0
*/
public static String getMethodName() {
Throwable throwable = new Throwable();
String methodName = "";
StackTraceElement[] stackTrace = throwable.getStackTrace();
if (stackTrace != null) {
if(stackTrace.length > 1){
methodName = stackTrace[1].getMethodName();
}
}
return methodName;
}
}
| 19.25 | 93 | 0.692208 |
c717de39a60cecca26fa0d54429f86652f7ae825 | 2,284 | /*
* Copyright 2015-2018 Micro Focus International plc.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.hod.sso;
import com.hp.autonomy.hod.client.api.authentication.AuthenticationToken;
import com.hp.autonomy.hod.client.api.authentication.EntityType;
import com.hp.autonomy.hod.client.api.authentication.TokenType;
import org.springframework.security.authentication.AbstractAuthenticationToken;
/**
* An Authentication representing an unverified Micro Focus Haven OnDemand combined SSO token.
* <p>
* This authentication is never authenticated.
*/
public class HodTokenAuthentication<E extends EntityType> extends AbstractAuthenticationToken {
private static final long serialVersionUID = -643920242131375593L;
private AuthenticationToken<E, TokenType.Simple> token;
public HodTokenAuthentication(final AuthenticationToken<E, TokenType.Simple> token) {
super(null);
super.setAuthenticated(false);
this.token = token;
}
/**
* @return The Micro Focus Haven OnDemand combined token
*/
@Override
public AuthenticationToken<E, TokenType.Simple> getCredentials() {
return token;
}
/**
* This method returns null as the user details have not been obtained yet
*
* @return null
*/
@Override
public Object getPrincipal() {
return null;
}
/**
* Sets the trusted state of the authentication. This can only be set to false. Since the authentication's initial
* state is false, there is no need to call this method
*
* @param isAuthenticated True if the token should be trusted; false otherwise
* @throws IllegalArgumentException If isAuthenticated is set to true
*/
@Override
public void setAuthenticated(final boolean isAuthenticated) {
if (isAuthenticated) {
throw new IllegalArgumentException("Cannot set this token to trusted");
}
super.setAuthenticated(false);
}
/**
* Removes the Micro Focus Haven OnDemand combined token from the authentication
*/
@Override
public void eraseCredentials() {
super.eraseCredentials();
token = null;
}
}
| 31.722222 | 118 | 0.704466 |
2279317c3d1d014f9aa898bf39050da6fd195e2a | 1,998 | // Template Source: Enum.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models.generated;
/**
* The Enum Certificate Issuance States.
*/
public enum CertificateIssuanceStates
{
/**
* unknown
*/
UNKNOWN,
/**
* challenge Issued
*/
CHALLENGE_ISSUED,
/**
* challenge Issue Failed
*/
CHALLENGE_ISSUE_FAILED,
/**
* request Creation Failed
*/
REQUEST_CREATION_FAILED,
/**
* request Submit Failed
*/
REQUEST_SUBMIT_FAILED,
/**
* challenge Validation Succeeded
*/
CHALLENGE_VALIDATION_SUCCEEDED,
/**
* challenge Validation Failed
*/
CHALLENGE_VALIDATION_FAILED,
/**
* issue Failed
*/
ISSUE_FAILED,
/**
* issue Pending
*/
ISSUE_PENDING,
/**
* issued
*/
ISSUED,
/**
* response Processing Failed
*/
RESPONSE_PROCESSING_FAILED,
/**
* response Pending
*/
RESPONSE_PENDING,
/**
* enrollment Succeeded
*/
ENROLLMENT_SUCCEEDED,
/**
* enrollment Not Needed
*/
ENROLLMENT_NOT_NEEDED,
/**
* revoked
*/
REVOKED,
/**
* removed From Collection
*/
REMOVED_FROM_COLLECTION,
/**
* renew Verified
*/
RENEW_VERIFIED,
/**
* install Failed
*/
INSTALL_FAILED,
/**
* installed
*/
INSTALLED,
/**
* delete Failed
*/
DELETE_FAILED,
/**
* deleted
*/
DELETED,
/**
* renewal Requested
*/
RENEWAL_REQUESTED,
/**
* requested
*/
REQUESTED,
/**
* For CertificateIssuanceStates values that were not expected from the service
*/
UNEXPECTED_VALUE
}
| 18 | 152 | 0.527528 |
2f68fe5de2a453aba6d4601cfa71f3ce83bf8b67 | 2,041 | package com.udma.core.tools.lang;
import java.security.MessageDigest;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.util.CollectionUtils;
public class StringUtil {
private static MessageDigest digest = null;
private StringUtil() throws InstantiationException {
throw new InstantiationException("StringUtil不支持实例化");
}
/**
* 替换字符串
*
* @apiNote 占位符请使用 ${xxx}
* @param sourceText 原文本文件
* @param param 替换的参数
* @return 替换后的结果
*/
public static String replaceAll(String sourceText, Map<String, String> param) {
if (CollectionUtils.isEmpty(param)) {
return sourceText;
}
Set<Map.Entry<String, String>> sets = param.entrySet();
for (Map.Entry<String, String> entry : sets) {
String regex = "\\$\\{" + entry.getKey() + "}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(sourceText);
if (entry.getValue() != null) {
sourceText = matcher.replaceAll(entry.getValue());
}
}
return sourceText;
}
/** 将字节数组转换为十六进制字符串 */
public static String byteToStr(byte[] byteArray) {
StringBuilder strDigest = new StringBuilder();
for (byte b : byteArray) {
strDigest.append(byteToHexStr(b));
}
return strDigest.toString();
}
/** 将字节转换为十六进制字符串 */
private static String byteToHexStr(byte mByte) {
char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
return new String(tempArr);
}
public static boolean containerLetter(CharSequence character) {
if (character == null || character.length() == 0) {
return false;
}
for (int i = 0; i < character.length(); i++) {
char c = character.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
return true;
}
}
return false;
}
}
| 27.958904 | 100 | 0.612935 |
2acff4c0ee191fd6ce2c9da646044b1e66be43b3 | 82 | package org.locationtech.geomesa.plugin.wps;
public interface GeomesaProcess {
}
| 16.4 | 44 | 0.817073 |
3c9f9e09c107ac9b4cd0447ad5f217e7689ff105 | 5,411 | package beans;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.*;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import database.DBClinReason;
import database.DBEditing;
import util.CRTLogger;
import beans.scripts.*;
import beans.user.User;
import controller.AjaxController;
import controller.NavigationController;
import controller.ScriptCopyController;
/**
* all scripts of an expert, needed for the overview/portfolio page to display a list.
*
*/
@ManagedBean(name = "expport", eager = true)
@SessionScoped
public class ExpPortfolio implements Serializable{
private static final long serialVersionUID = 1L;
private User user;
private List<PatientIllnessScript> expscripts;
public ExpPortfolio(User u ){
this.user =u;
loadScripts();
}
/** expert maps the admin has access to
* @return
*/
public List<PatientIllnessScript> getExpscripts() {return expscripts;}
public void addExpertScript(PatientIllnessScript script){
if(script==null) return;
if(expscripts==null) expscripts = new ArrayList<PatientIllnessScript>();
expscripts.add(script);
}
/**
* if no scripts are available for this user, we display a message
* @return
*/
public String getNoscripts(){
if(expscripts==null || expscripts.isEmpty()) return "No scripts available.";
return "";
}
/**
* TODO: later on we have to consider the userId to load only scripts that are editable by the current user.
*/
private void loadScripts(){
if(expscripts==null){
if(user.isAdmin())
expscripts = new DBEditing().selectAllExpertPatIllScripts();
else expscripts = new DBEditing().selectAllExpertPatIllScriptsByUserId(user.getUserId());
}
}
public PatientIllnessScript getExpScriptById(long id){
if(expscripts==null) return null;
Iterator<PatientIllnessScript> it = expscripts.iterator();
while(it.hasNext()){
PatientIllnessScript scr = it.next();
if(scr.getId()==id) return scr;
}
return null;
}
public PatientIllnessScript getExpScriptByVPId(String vpId){
if(expscripts==null) return null;
Iterator<PatientIllnessScript> it = expscripts.iterator();
while(it.hasNext()){
PatientIllnessScript scr = it.next();
if(scr.getVpId().equalsIgnoreCase(vpId)) return scr;
}
return null;
}
/**
* A new expert script is created and stored into the database
*/
public PatientIllnessScript createNewExpScript(){
CRTLogger.out("Create new script", CRTLogger.LEVEL_PROD);
String vpId = AjaxController.getInstance().getRequestParamByKey(AjaxController.REQPARAM_VP);
String systemId = AjaxController.getInstance().getRequestParamByKey(AjaxController.REQPARAM_SYSTEM);
if(!vpId.contains("_")) vpId = vpId + "_" +systemId;
String lang = AjaxController.getInstance().getRequestParamByKey(AjaxController.REQPARAM_SCRIPTLOC);
if(lang==null || lang.isEmpty()) lang = "en";
PatientIllnessScript patillscript = new PatientIllnessScript(user.getUserId(), vpId, new Locale(lang), 2);
int maxStage = AjaxController.getInstance().getIntRequestParamByKey(AjaxController.REQPARAM_MAXSTAGE, -1);
int maxddxstage = AjaxController.getInstance().getIntRequestParamByKey("maxddxstage", -1);
patillscript.iniExpertScript(maxStage, maxddxstage);
new DBClinReason().saveAndCommit(patillscript);
String vpName = AjaxController.getInstance().getRequestParamByKeyNoDecrypt(AjaxController.REQPARAM_VP_NAME);
VPScriptRef ref= new VPScriptRef(patillscript.getVpId(), vpName, 2, vpId);
new DBClinReason().saveAndCommit(ref);
addExpertScript(patillscript);
CRTLogger.out("Create new script: id= " + patillscript.getId(), CRTLogger.LEVEL_PROD);
return patillscript;
}
/**
* We trigger the copying and translating of an expert script...
* @deprecated here...
*/
public void copyExpScript(){
CRTLogger.out("Copy script", CRTLogger.LEVEL_PROD);
String orgVpId = AjaxController.getInstance().getRequestParamByKey("org_vp_id");
String newVPId = AjaxController.getInstance().getRequestParamByKey("new_vp_id");
String lang = AjaxController.getInstance().getRequestParamByKey(AjaxController.REQPARAM_SCRIPTLOC);
ScriptCopyController.initCopyAndTranslate(orgVpId, newVPId, lang);
}
/**
* We check whether an expert script for a vp_id has been created. If not we trigger the creation.
*/
public PatientIllnessScript getOrCreateExpScriptFromVPSystem(){
CRTLogger.out("Create new script", CRTLogger.LEVEL_PROD);
String vpId = AjaxController.getInstance().getRequestParamByKey(AjaxController.REQPARAM_VP);
String systemId = AjaxController.getInstance().getRequestParamByKey(AjaxController.REQPARAM_SYSTEM);
int maxstage = AjaxController.getInstance().getIntRequestParamByKey(AjaxController.REQPARAM_MAXSTAGE, -1);
PatientIllnessScript patillscript = new DBClinReason().selectExpertPatIllScriptByVPId(vpId+"_"+systemId);
if(patillscript!=null){
if(maxstage>0 && patillscript.getStage()!=maxstage) patillscript.setCurrentStage(maxstage);
patillscript.setLastAccessDate(new Timestamp(System.currentTimeMillis()));
new DBClinReason().saveAndCommit(patillscript);
return patillscript;
}
//not yet created
return createNewExpScript();
}
/**
* called from the overview page to avoid caching issues
*/
public boolean getInit(){
NavigationController.getInstance().getAdminFacesContext().setPatillscript(null);
return true;
}
}
| 34.464968 | 110 | 0.760673 |
1e42b147dc21f5a7725d72180079ccace5cd02bb | 19,144 | /*
* Copyright (C) 2013 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sample.castcompanionlibrary.notification;
import static com.google.sample.castcompanionlibrary.utils.LogUtils.LOGD;
import static com.google.sample.castcompanionlibrary.utils.LogUtils.LOGE;
import com.google.android.gms.cast.MediaInfo;
import com.google.android.gms.cast.MediaMetadata;
import com.google.android.gms.cast.MediaStatus;
import com.google.sample.castcompanionlibrary.R;
import com.google.sample.castcompanionlibrary.cast.VideoCastManager;
import com.google.sample.castcompanionlibrary.cast.callbacks.VideoCastConsumerImpl;
import com.google.sample.castcompanionlibrary.cast.exceptions.CastException;
import com.google.sample.castcompanionlibrary.cast.exceptions.NoConnectionException;
import com.google.sample.castcompanionlibrary.cast.exceptions.TransientNetworkDisconnectionException;
import com.google.sample.castcompanionlibrary.cast.player.VideoCastControllerActivity;
import com.google.sample.castcompanionlibrary.utils.FetchBitmapTask;
import com.google.sample.castcompanionlibrary.utils.LogUtils;
import com.google.sample.castcompanionlibrary.utils.Utils;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.RemoteViews;
/**
* A service to provide status bar Notifications when we are casting. For JB+ versions, notification
* area provides a play/pause toggle and an "x" button to disconnect but that for GB, we do not
* show that due to the framework limitations.
*/
public class VideoCastNotificationService extends Service {
private static final String TAG = LogUtils.makeLogTag(VideoCastNotificationService.class);
public static final String ACTION_TOGGLE_PLAYBACK =
"com.google.sample.castcompanionlibrary.action.toggleplayback";
public static final String ACTION_STOP =
"com.google.sample.castcompanionlibrary.action.stop";
public static final String ACTION_VISIBILITY =
"com.google.sample.castcompanionlibrary.action.notificationvisibility";
private static final int NOTIFICATION_ID = 1;
public static final String NOTIFICATION_VISIBILITY = "visible";
private String mApplicationId;
private Bitmap mVideoArtBitmap;
private Uri mVideoArtUri;
private boolean mIsPlaying;
private Class<?> mTargetActivity;
private String mDataNamespace;
private int mStatus;
private int mOldStatus = -1;
private Notification mNotification;
private boolean mVisible;
boolean mIsIcsOrAbove = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
boolean mIsLollipopOrAbove = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
private VideoCastManager mCastManager;
private VideoCastConsumerImpl mConsumer;
private FetchBitmapTask mBitmapDecoderTask;
@Override
public void onCreate() {
super.onCreate();
LOGD(TAG, "onCreate()");
readPersistedData();
mCastManager = VideoCastManager
.initialize(this, mApplicationId, mTargetActivity, mDataNamespace);
if (!mCastManager.isConnected() && !mCastManager.isConnecting()) {
mCastManager.reconnectSessionIfPossible(this, false);
}
mConsumer = new VideoCastConsumerImpl() {
@Override
public void onApplicationDisconnected(int errorCode) {
LOGD(TAG, "onApplicationDisconnected() was reached, stopping the notification"
+ " service");
stopSelf();
}
@Override
public void onRemoteMediaPlayerStatusUpdated() {
int mediaStatus = mCastManager.getPlaybackStatus();
VideoCastNotificationService.this.onRemoteMediaPlayerStatusUpdated(mediaStatus);
}
@Override
public void onUiVisibilityChanged(boolean visible) {
mVisible = !visible;
if (mVisible && null != mNotification) {
startForeground(NOTIFICATION_ID, mNotification);
mCastManager.setContext(VideoCastNotificationService.this);
} else {
stopForeground(true);
}
}
};
mCastManager.addVideoCastConsumer(mConsumer);
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
LOGD(TAG, "onStartCommand");
if (null != intent) {
String action = intent.getAction();
if (ACTION_TOGGLE_PLAYBACK.equals(action) && mIsIcsOrAbove) {
LOGD(TAG, "onStartCommand(): Action: ACTION_TOGGLE_PLAYBACK");
togglePlayback();
} else if (ACTION_STOP.equals(action) && mIsIcsOrAbove) {
LOGD(TAG, "onStartCommand(): Action: ACTION_STOP");
stopApplication();
} else if (ACTION_VISIBILITY.equals(action)) {
mVisible = intent.getBooleanExtra(NOTIFICATION_VISIBILITY, false);
LOGD(TAG, "onStartCommand(): Action: ACTION_VISIBILITY " + mVisible);
if (mVisible && null != mNotification) {
startForeground(NOTIFICATION_ID, mNotification);
mCastManager.setContext(this);
} else {
stopForeground(true);
}
} else {
LOGD(TAG, "onStartCommand(): Action: none");
}
} else {
LOGD(TAG, "onStartCommand(): Intent was null");
}
return Service.START_STICKY;
}
private void setupNotification(final MediaInfo info)
throws TransientNetworkDisconnectionException, NoConnectionException {
if (null == info) {
return;
}
if (null != mBitmapDecoderTask) {
mBitmapDecoderTask.cancel(false);
}
Uri imgUri = null;
try {
if (!info.getMetadata().hasImages()) {
build(info, null, mIsPlaying);
return;
} else {
imgUri = info.getMetadata().getImages().get(0).getUrl();
if (imgUri.equals(mVideoArtUri)) {
build(info, mVideoArtBitmap, mIsPlaying);
return ;
}
}
} catch (CastException e) {
LOGE(TAG, "Failed to build notification");
}
mBitmapDecoderTask = new FetchBitmapTask(400, 400) {
@Override
protected void onPostExecute(Bitmap bitmap) {
try {
mVideoArtBitmap = Utils.scaleCenterCrop(bitmap, 256, 256);
build(info, mVideoArtBitmap, mIsPlaying);
} catch (CastException e) {
LOGE(TAG, "Failed to set notification for " + info.toString(), e);
} catch (TransientNetworkDisconnectionException e) {
LOGE(TAG, "Failed to set notification for " + info.toString(), e);
} catch (NoConnectionException e) {
LOGE(TAG, "Failed to set notification for " + info.toString(), e);
}
if (mVisible) {
startForeground(NOTIFICATION_ID, mNotification);
}
if (this == mBitmapDecoderTask) {
mBitmapDecoderTask = null;
}
}
};
mBitmapDecoderTask.start(imgUri);
}
/**
* Removes the existing notification.
*/
private void removeNotification() {
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).
cancel(NOTIFICATION_ID);
}
private void onRemoteMediaPlayerStatusUpdated(int mediaStatus) {
mStatus = mediaStatus;
if (mOldStatus == mStatus) {
// not need to make any updates here
return;
}
mOldStatus = mStatus;
LOGD(TAG, "onRemoteMediaPlayerStatusUpdated() reached with status: " + mStatus);
try {
switch (mediaStatus) {
case MediaStatus.PLAYER_STATE_BUFFERING: // (== 4)
mIsPlaying = false;
setupNotification(mCastManager.getRemoteMediaInformation());
break;
case MediaStatus.PLAYER_STATE_PLAYING: // (== 2)
mIsPlaying = true;
setupNotification(mCastManager.getRemoteMediaInformation());
break;
case MediaStatus.PLAYER_STATE_PAUSED: // (== 3)
mIsPlaying = false;
setupNotification(mCastManager.getRemoteMediaInformation());
break;
case MediaStatus.PLAYER_STATE_IDLE: // (== 1)
mIsPlaying = false;
if (!mCastManager.shouldRemoteUiBeVisible(mediaStatus,
mCastManager.getIdleReason())) {
stopForeground(true);
} else {
setupNotification(mCastManager.getRemoteMediaInformation());
}
break;
case MediaStatus.PLAYER_STATE_UNKNOWN: // (== 0)
mIsPlaying = false;
stopForeground(true);
break;
default:
break;
}
} catch (TransientNetworkDisconnectionException e) {
LOGE(TAG, "Failed to update the playback status due to network issues", e);
} catch (NoConnectionException e) {
LOGE(TAG, "Failed to update the playback status due to network issues", e);
}
}
/*
* (non-Javadoc)
* @see android.app.Service#onDestroy()
*/
@Override
public void onDestroy() {
if (null != mBitmapDecoderTask) {
mBitmapDecoderTask.cancel(false);
}
LOGD(TAG, "onDestroy was called");
removeNotification();
if (null != mCastManager && null != mConsumer) {
mCastManager.removeVideoCastConsumer(mConsumer);
mCastManager = null;
}
}
/*
* Build the RemoteViews for the notification. We also need to add the appropriate "back stack"
* so when user goes into the CastPlayerActivity, she can have a meaningful "back" experience.
*/
private RemoteViews build(MediaInfo info, Bitmap bitmap, boolean isPlaying)
throws CastException, TransientNetworkDisconnectionException, NoConnectionException {
Log.d(TAG, "Build version is: " + Build.VERSION.SDK_INT);
if (mIsLollipopOrAbove) {
buildForLollipopAndAbove(info, bitmap, isPlaying);
return null;
}
Bundle mediaWrapper = Utils.fromMediaInfo(mCastManager.getRemoteMediaInformation());
Intent contentIntent = new Intent(this, mTargetActivity);
contentIntent.putExtra("media", mediaWrapper);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(mTargetActivity);
stackBuilder.addNextIntent(contentIntent);
if (stackBuilder.getIntentCount() > 1) {
stackBuilder.editIntentAt(1).putExtra("media", mediaWrapper);
}
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(NOTIFICATION_ID, PendingIntent.FLAG_UPDATE_CURRENT);
MediaMetadata mm = info.getMetadata();
RemoteViews rv = new RemoteViews(getPackageName(), R.layout.custom_notification);
if (mIsIcsOrAbove) {
addPendingIntents(rv, isPlaying, info);
}
if (null != bitmap) {
rv.setImageViewBitmap(R.id.iconView, bitmap);
} else {
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.dummy_album_art);
rv.setImageViewBitmap(R.id.iconView, bitmap);
}
rv.setTextViewText(R.id.titleView, mm.getString(MediaMetadata.KEY_TITLE));
String castingTo = getResources().getString(R.string.casting_to_device,
mCastManager.getDeviceName());
rv.setTextViewText(R.id.subTitleView, castingTo);
mNotification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_action_notification)
.setContentIntent(resultPendingIntent)
.setContent(rv)
.setAutoCancel(false)
.setOngoing(true)
.build();
// to get around a bug in GB version, we add the following line
// see https://code.google.com/p/android/issues/detail?id=30495
mNotification.contentView = rv;
return rv;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void buildForLollipopAndAbove(MediaInfo info, Bitmap bitmap, boolean isPlaying)
throws CastException, TransientNetworkDisconnectionException, NoConnectionException {
// Playback PendingIntent
Intent playbackIntent = new Intent(ACTION_TOGGLE_PLAYBACK);
playbackIntent.setPackage(getPackageName());
PendingIntent playbackPendingIntent = PendingIntent
.getBroadcast(this, 0, playbackIntent, 0);
// Disconnect PendingIntent
Intent stopIntent = new Intent(ACTION_STOP);
stopIntent.setPackage(getPackageName());
PendingIntent stopPendingIntent = PendingIntent.getBroadcast(this, 0, stopIntent, 0);
// Main Content PendingIntent
Bundle mediaWrapper = Utils.fromMediaInfo(mCastManager.getRemoteMediaInformation());
Intent contentIntent = new Intent(this, mTargetActivity);
contentIntent.putExtra("media", mediaWrapper);
// Media metadata
MediaMetadata mm = info.getMetadata();
String castingTo = getResources().getString(R.string.casting_to_device,
mCastManager.getDeviceName());
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(mTargetActivity);
stackBuilder.addNextIntent(contentIntent);
if (stackBuilder.getIntentCount() > 1) {
stackBuilder.editIntentAt(1).putExtra("media", mediaWrapper);
}
PendingIntent contentPendingIntent =
stackBuilder.getPendingIntent(NOTIFICATION_ID, PendingIntent.FLAG_UPDATE_CURRENT);
mNotification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_stat_action_notification)
.setContentTitle(mm.getString(MediaMetadata.KEY_TITLE))
.setContentText(castingTo)
.setContentIntent(contentPendingIntent)
.setLargeIcon(bitmap)
.addAction(isPlaying ? R.drawable.ic_av_pause_light : R.drawable.ic_av_play_light,
"Pause", playbackPendingIntent)
.addAction(R.drawable.ic_cast_stop, "Disconnect", stopPendingIntent)
.setStyle(new Notification.MediaStyle()
.setShowActionsInCompactView(new int[]{0,1}))
.setOngoing(true)
.setShowWhen(false)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.build();
}
private void addPendingIntents(RemoteViews rv, boolean isPlaying, MediaInfo info) {
Intent playbackIntent = new Intent(ACTION_TOGGLE_PLAYBACK);
playbackIntent.setPackage(getPackageName());
PendingIntent playbackPendingIntent = PendingIntent
.getBroadcast(this, 0, playbackIntent, 0);
Intent stopIntent = new Intent(ACTION_STOP);
stopIntent.setPackage(getPackageName());
PendingIntent stopPendingIntent = PendingIntent.getBroadcast(this, 0, stopIntent, 0);
rv.setOnClickPendingIntent(R.id.playPauseView, playbackPendingIntent);
rv.setOnClickPendingIntent(R.id.removeView, stopPendingIntent);
if (isPlaying) {
if (info.getStreamType() == MediaInfo.STREAM_TYPE_LIVE) {
rv.setImageViewResource(R.id.playPauseView, R.drawable.ic_av_stop_sm_dark);
} else {
rv.setImageViewResource(R.id.playPauseView, R.drawable.ic_av_pause_sm_dark);
}
} else {
rv.setImageViewResource(R.id.playPauseView, R.drawable.ic_av_play_sm_dark);
}
}
private void togglePlayback() {
try {
mCastManager.togglePlayback();
} catch (Exception e) {
LOGE(TAG, "Failed to toggle the playback", e);
}
}
/*
* We try to disconnect application but even if that fails, we need to remove notification since
* that is the only way to get rid of it without going to the application
*/
private void stopApplication() {
try {
LOGD(TAG, "Calling stopApplication");
mCastManager.disconnect();
} catch (Exception e) {
LOGE(TAG, "Failed to disconnect application", e);
}
LOGD(TAG, "Stopping the notification service");
stopSelf();
}
/*
* Reads application ID and target activity from preference storage.
*/
private void readPersistedData() {
mApplicationId = Utils.getStringFromPreference(
this, VideoCastManager.PREFS_KEY_APPLICATION_ID);
String targetName = Utils.getStringFromPreference(
this, VideoCastManager.PREFS_KEY_CAST_ACTIVITY_NAME);
mDataNamespace = Utils.getStringFromPreference(
this, VideoCastManager.PREFS_KEY_CAST_CUSTOM_DATA_NAMESPACE);
try {
if (null != targetName) {
mTargetActivity = Class.forName(targetName);
} else {
mTargetActivity = VideoCastControllerActivity.class;
}
} catch (ClassNotFoundException e) {
LOGE(TAG, "Failed to find the targetActivity class", e);
}
}
}
| 41.258621 | 101 | 0.634141 |
209707e3a0d3daa12dedd47da707d09a712d1fda | 206 | package msifeed.misca.charstate;
import net.minecraft.util.ResourceLocation;
public class ItemEffectInfo {
public ResourceLocation effect;
public int duration = 0;
public int amplifier = 0;
}
| 20.6 | 43 | 0.757282 |
7bda8e2c4187e4e84026277ea4937aefc66e2ba0 | 628 | package com.apigee.messagee;
import android.app.Activity;
import android.os.Bundle;
/* This class is a convenience class that will automatically initialize our Apigee client
* if it's not already been called. It should be extended by all Activities in the application.
*/
public class ApigeeActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Messagee messagee = (Messagee) this.getApplication();
if (null == messagee.messController.getApigeeClient()) {
messagee.messController.apigeeInitialize(this.getApplicationContext());
}
}
}
| 28.545455 | 95 | 0.773885 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.