text
stringlengths
7
1.01M
package com.executor.TestObj; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.executor.core.Exec; import com.executor.execute.Parameters; public class Test { List<String> ls = new ArrayList<>(); Test2 ts = new Test2("", "", ""); {Parameters.set(ts);} public TestAgain print(Test2 t) { return new TestAgain(); } }
package com.example.administrator.project; import android.app.Activity; import android.os.Bundle; /** * Created by Administrator on 2015/12/5. */ public class Row3Col2Activity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lianxiwomen); } }
package org.javamaster.b2c.mybatistk.enums; /** * Created on 2018/11/15.<br/> * * @author yudong */ public enum VisibleEnum { SHOW(1, "展示"), HIDE(0, "隐藏"); private Integer code; private String msg; VisibleEnum(Integer code, String msg) { this.code = code; this.msg = msg; } public Integer getCode() { return code; } public String getMsg() { return msg; } }
/** * Copyright Indra Soluciones Tecnologías de la Información, S.L.U. * 2013-2019 SPAIN * * 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.minsait.onesait.platform.config.services.project; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import com.minsait.onesait.platform.commons.metrics.MetricsManager; import com.minsait.onesait.platform.config.model.App; import com.minsait.onesait.platform.config.model.AppRole; import com.minsait.onesait.platform.config.model.AppUser; import com.minsait.onesait.platform.config.model.Project; import com.minsait.onesait.platform.config.model.ProjectResourceAccess; import com.minsait.onesait.platform.config.model.Role; import com.minsait.onesait.platform.config.model.User; import com.minsait.onesait.platform.config.model.WebProject; import com.minsait.onesait.platform.config.model.base.OPResource; import com.minsait.onesait.platform.config.repository.ProjectRepository; import com.minsait.onesait.platform.config.services.app.AppService; import com.minsait.onesait.platform.config.services.user.UserService; import com.minsait.onesait.platform.config.services.webproject.WebProjectService; import avro.shaded.com.google.common.collect.Lists; @Service public class ProjectServiceImpl implements ProjectService { @Autowired private ProjectRepository projectRepository; @Autowired private AppService appService; @Autowired private UserService userService; @Autowired private WebProjectService webProjectService; @Autowired(required = false) private MetricsManager metricsManager; @Override public Project createProject(ProjectDTO project) { Project p = new Project(); p.setName(project.getName()); p.setDescription(project.getDescription()); p.setType(project.getType()); p.setUser(project.getUser()); p = projectRepository.save(p); if (null != metricsManager) { metricsManager.logControlPanelProjectsCreation(project.getUser().getUserId(), "OK"); } return p; } @Override @Transactional public void deleteProject(String projectId) { final Project project = projectRepository.findOne(projectId); final App app = project.getApp(); if (app != null) { project.setApp(null); app.setProject(null); appService.updateApp(app); } if (!project.getUsers().isEmpty()) { removeUsersFromProject(project); project.getUsers().clear(); } projectRepository.delete(project); } @Override public List<Project> getAllProjects() { return projectRepository.findAll(); } @Override public Project getById(String id) { return projectRepository.findOne(id); } @Override @Transactional public void updateProject(Project project) { projectRepository.save(project); } @Override public void updateWithParameters(ProjectDTO project) { final Project projectDb = projectRepository.findOne(project.getId()); projectDb.setDescription(project.getDescription()); projectDb.setType(project.getType()); projectRepository.save(projectDb); } @Override @Transactional public List<ProjectUserDTO> getProjectMembers(String projectId) { final Project project = projectRepository.findOne(projectId); if (project != null) { final List<?> users = getProjectUsers(project); return getMembersDTO(users); } else { return new ArrayList<>(); } } private List<?> getProjectUsers(Project project) { if (project.getApp() != null) { final List<AppUser> users = new ArrayList<>(); final App app = project.getApp(); if (!CollectionUtils.isEmpty(app.getChildApps())) { app.getChildApps().forEach(a -> a.getAppRoles().forEach(r -> r.getAppUsers().forEach(au -> { if (!users.contains(au)) users.add(au); }) )); } app.getAppRoles().forEach(r -> r.getAppUsers().forEach(au -> { if (!users.contains(au)) users.add(au); })); return users; } else { return Lists.newArrayList(project.getUsers()); } } private List<ProjectUserDTO> getMembersDTO(List<?> members) { return members.stream().map(o -> { if (o instanceof AppUser) return ProjectUserDTO.builder().userId(((AppUser) o).getUser().getUserId()) .roleName(((AppUser) o).getRole().getName()).fullName(((AppUser) o).getUser().getFullName()) .realm(((AppUser) o).getRole().getApp().getAppId()).build(); else if (o instanceof User) return ProjectUserDTO.builder().userId(((User) o).getUserId()).roleName(((User) o).getRole().getId()) .fullName(((User) o).getFullName()).build(); else return null; }).filter(Objects::nonNull).collect(Collectors.toList()); } @Override public List<App> getAvailableRealmsForUser(String userId) { return appService.getAppsByUser(userId, null).stream().filter(a -> a.getProject() == null) .collect(Collectors.toList()); } @Override @Transactional public List<Project> getProjectsForUser(String userId) { final List<Project> projects = projectRepository.findAll(); final User user = userService.getUser(userId); if (user.getRole().getId().equals(Role.Type.ROLE_ADMINISTRATOR.name())) return projects; final List<Project> filteredProjects = projects.stream() .filter(p -> p.getUser().equals(user) || p.getUsers().contains(user)).collect(Collectors.toList()); projects.forEach(p -> addAppRelatedProjects(p, filteredProjects, user)); return filteredProjects; } private void addAppRelatedProjects(Project p, List<Project> filteredProjects, User user) { if (p.getApp() != null) { final App app = p.getApp(); if (!CollectionUtils.isEmpty(app.getChildApps())) { app.getChildApps().forEach(a -> a.getAppRoles().forEach(r -> { final List<User> users = r.getAppUsers().stream().map(AppUser::getUser) .collect(Collectors.toList()); if (users.contains(user) && !filteredProjects.contains(p)) filteredProjects.add(p); })); } app.getAppRoles().forEach(r -> { final List<User> users = r.getAppUsers().stream().map(AppUser::getUser).collect(Collectors.toList()); if (users.contains(user) && !filteredProjects.contains(p)) filteredProjects.add(p); }); } } @Override @Transactional public void addUserToProject(String userId, String projectId) { final User user = userService.getUser(userId); final Project project = projectRepository.findOne(projectId); if (user != null && project != null && project.getApp() == null) { project.getUsers().add(user); user.getProjects().add(project); projectRepository.save(project); userService.saveExistingUser(user); } } @Override @Transactional public void removeUserFromProject(String userId, String projectId) { final User user = userService.getUser(userId); final Project project = projectRepository.findOne(projectId); if (user != null && project != null && project.getApp() == null) { project.getUsers().remove(user); user.getProjects().remove(project); project.getProjectResourceAccesses().removeIf(pra -> pra.getUser().equals(user)); projectRepository.save(project); userService.saveExistingUser(user); } } private void removeUsersFromProject(Project project) { if (project != null && project.getApp() == null && !project.getUsers().isEmpty()) { project.getUsers().stream().forEach(u -> { u.getProjects().remove(project); userService.saveExistingUser(u); }); } } @Override @Transactional public void setRealm(String realmId, String projectId) { final App app = appService.getByIdentification(realmId); if (app != null) { final Project project = projectRepository.findOne(projectId); if (!project.getUsers().isEmpty()) project.getUsers().clear(); project.setApp(app); app.setProject(project); projectRepository.save(project); appService.updateApp(app); } } @Override @Transactional public void unsetRealm(String realmId, String projectId) { final App app = appService.getByIdentification(realmId); if (app != null) { final Project project = projectRepository.findOne(projectId); project.setApp(null); app.setProject(null); project.getProjectResourceAccesses().clear(); projectRepository.save(project); appService.updateApp(app); } } @Override public void addWebProject(String webProjectId, String projectId, String userId) { final Project project = projectRepository.findOne(projectId); final WebProject webProject = webProjectService.getWebProjectById(webProjectId, userId); if (webProject != null && project != null) { project.setWebProject(webProject); projectRepository.save(project); } } @Override public void removeWebProject(String projectId) { final Project project = projectRepository.findOne(projectId); if (project != null) { project.setWebProject(null); projectRepository.save(project); } } @Override @Transactional public boolean isUserInProject(String userId, String projectId) { final User user = userService.getUser(userId); final Project project = projectRepository.findOne(projectId); if (project.getUser().equals(user)) return true; else if (project.getApp() != null) return project.getApp().getAppRoles().stream() .map(ar -> ar.getAppUsers().stream().map(au -> au.getUser().equals(user)) .filter(Boolean::booleanValue).findFirst().orElse(false)) .filter(Boolean::booleanValue).findFirst().orElse(false); else return project.getUsers().contains(user); } @Override public Set<ProjectResourceAccess> getResourcesAccessesForUser(String projectId, String userId) { final User user = userService.getUser(userId); final Project project = projectRepository.findOne(projectId); if (project.getApp() != null) { final Set<AppRole> roles = project .getApp().getAppRoles().stream().filter(ar -> null != ar.getAppUsers().stream() .map(AppUser::getUser).filter(u -> u.equals(user)).findFirst().orElse(null)) .collect(Collectors.toSet()); return project.getProjectResourceAccesses().stream().filter(pra -> roles.contains(pra.getAppRole())) .collect(Collectors.toSet()); } else { return project.getProjectResourceAccesses().stream().filter(pra -> pra.getUser().equals(user)) .collect(Collectors.toSet()); } } @Override public Set<OPResource> getResourcesForProjectAndUser(String projectId, String userId) { final User user = userService.getUser(userId); final Project project = projectRepository.findOne(projectId); final String role_user = user.getRole().getId(); if (user.equals(project.getUser()) || role_user.equals(Role.Type.ROLE_ADMINISTRATOR.toString())) return project.getProjectResourceAccesses().stream().map(ProjectResourceAccess::getResource) .collect(Collectors.toSet()); else return getResourcesAccessesForUser(projectId, userId).stream().map(ProjectResourceAccess::getResource) .collect(Collectors.toSet()); } @Override @Transactional public Set<OPResource> getResourcesForUser(String userId) { final Set<OPResource> resources = new HashSet<>(); final User user = userService.getUser(userId); final List<Project> projects = getProjectsForUser(userId); if (null == user || projects.isEmpty()) return resources; projects.stream().forEach(p -> resources.addAll(getResourcesForProjectAndUser(p.getId(), userId))); return resources; } @Override @Transactional public <T> Set<T> getResourcesForUserOfType(String userId, Class<T> clazz) { return getResourcesForUser(userId).stream().filter(clazz::isInstance).map(clazz::cast) .collect(Collectors.toSet()); } @Override @Transactional public Set<AppRole> getProjectRoles(String projectId) { final Set<AppRole> roles = new HashSet<>(); final Project project = projectRepository.findOne(projectId); roles.addAll(project.getApp().getAppRoles()); project.getApp().getChildApps().forEach(a -> roles.addAll(a.getAppRoles())); return roles; } @Override public boolean isUserAuthorized(String projectId, String userId) { final Project project = projectRepository.findOne(projectId); final User user = userService.getUser(userId); return (project.getUser().equals(user) || user.getRole().getId().equals(Role.Type.ROLE_ADMINISTRATOR.name())); } }
package com.brainfucker; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.ArrayList; import java.util.regex.*; public class Population { private List<Individual> testPrograms; private List<Individual> buffer; private int population; private double elitismRate; private double mutationRate; private String desiredOutput; private static final Range RANGE = new Range(40,120); public Population(int population, double elitismRate, double mutationRate, String desiredOutput) { this.population = population; this.elitismRate = elitismRate; this.mutationRate = mutationRate; this.desiredOutput = desiredOutput; /*! * Sets up the testPrograms and the buffer with default values, random for programs and empty for buffer */ testPrograms = new ArrayList<Individual>(population); buffer = new ArrayList<Individual>(population); } public List<Individual> getTestPrograms() { return testPrograms; } /*! * Initializes the population and the buffer, though the buffer is merely empty */ public void initPopulation() { for (int i = 0; i < population; i++) { Individual temp = new Individual(RANGE); testPrograms.add(temp); buffer.add(temp); } } /*! * Swaps the population and the buffer */ public void swap() { testPrograms = buffer; buffer = new ArrayList<Individual>(); for (int i = 0; i < population; i++) { Individual temp = new Individual(RANGE); buffer.add(temp); } } /*! * Passes the Elites on to the buffer, requires the array be sorted in order to work * @return the number of elites used */ public int CalcElitism() { int numberElites = (int) (elitismRate * (double) population); for (int i = 0; i < numberElites; i++) { buffer.set(i, testPrograms.get(i)); buffer.get(i).mutate(2); } return numberElites; } /*! * Sorts the programs based off of their fitness */ public void sortPopulation() { Collections.sort(testPrograms); } /*! * Determines the fitness of each individual in the testPrograms array */ public void fitness() { int errorVal = 10000; BrainfuckRunner bRRunner = new BrainfuckRunner(); for (int i = 0; testPrograms.size() > i; i++) { int fitness = 0; //sample regex String output = bRRunner.run(testPrograms.get(i).getStringVal()); testPrograms.get(i).output = output; Pattern loopPattern = Pattern.compile("infinite\\sloop",Pattern.CASE_INSENSITIVE); Matcher loopMatcher = loopPattern.matcher(output); if (loopMatcher.find()) { testPrograms.get(i).fillRandomly(); fitness = errorVal; }else if (output.contains("<=$:$=>")) { fitness += errorVal; } else { for (int foo = 0; foo < desiredOutput.length(); foo++) { int charValDesired = desiredOutput.charAt(foo); int charValActual = (foo >= output.length()) ? 0 : output.charAt(foo); int difference = charValDesired - charValActual; fitness += (difference < 0) ? -difference : difference; } } //implement! testPrograms.get(i).fitness = fitness; } } /*! * Mates members of the population and adds them into the buffer * Mating approach is to cut the program in half and swap it out with another program * Activates elitism * Activates mutation of elemnents */ public void mate() { int numbElites = CalcElitism(); for (int i = numbElites; i < testPrograms.size() - 1; i += 2) { Individual parent1 = testPrograms.get(i); Individual parent2 = testPrograms.get(i + 1); String shortCode = (parent1.genes.length < parent2.genes.length) ? parent1.getStringVal() : parent2.getStringVal(); String longcode = (parent1.genes.length > parent2.genes.length) ? parent1.getStringVal() : parent2.getStringVal(); int breakpoint = (int) Math.round((double) shortCode.length() * 1.0 / 4.0) + (int) Math.round(Math.random() * (double) shortCode.length() * 3.0 / 4.0); while (breakpoint % 3 != 0) { breakpoint = (int) Math.round((double) shortCode.length() * 1.0 / 4.0) + (int) Math.round(Math.random() * (double) shortCode.length() * 3.0 / 4.0); } String codeOne = shortCode.substring(0, breakpoint) + longcode.substring(breakpoint, longcode.length()); String codeTwo = longcode.substring(0, breakpoint) + shortCode.substring(breakpoint, shortCode.length()); buffer.set(i, new Individual(codeOne)); buffer.set(i + 1, new Individual(codeTwo)); } } /*! * Prints the best program of the set */ public String getBest() { return testPrograms.get(0).getStringVal() + " fitness: " + testPrograms.get(0).fitness + " output :" + testPrograms.get(0).output; } }
/* * Copyright 2015-2019 Hippo B.V. (http://www.onehippo.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hippoecm.frontend.plugins.jquery.upload.single; import java.util.Map; import org.apache.wicket.Component; import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.event.Broadcast; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.JavaScriptHeaderItem; import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.request.resource.JavaScriptResourceReference; import org.apache.wicket.util.template.PackageTextTemplate; import org.hippoecm.frontend.plugins.jquery.upload.FileUploadBehavior; import org.hippoecm.frontend.plugins.jquery.upload.FileUploadWidgetSettings; import org.hippoecm.frontend.widgets.UpdateFeedbackInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Create an unique instance of jquery-file-upload widget. It does not work for multiple instances jquery-file-upload */ public class SingleFileUploadBar extends Panel { private static final Logger log = LoggerFactory.getLogger(SingleFileUploadBar.class); private static final String JQUERY_FILEUPLOAD_SINGLE_JS = "jquery.fileupload-single.js"; private static final String CONFIG_JS = "fileupload-single-config.js"; public SingleFileUploadBar(final String id, final FileUploadWidgetSettings settings) { super(id); setOutputMarkupId(true); AbstractDefaultAjaxBehavior refreshAjaxBehavior; add(refreshAjaxBehavior = new AbstractDefaultAjaxBehavior() { @Override protected void respond(final AjaxRequestTarget target) { log.debug("Received an ajax callback refreshing page"); target.add(SingleFileUploadBar.this.getPage()); // refresh feedback panel in EditPerspective if needed send(SingleFileUploadBar.this, Broadcast.BUBBLE, new UpdateFeedbackInfo(target)); } }); final AbstractDefaultAjaxBehavior onChangeAjaxBehavior; add(onChangeAjaxBehavior = new AbstractDefaultAjaxBehavior() { @Override protected void respond(final AjaxRequestTarget target) { onChange(target); } }); add(new FileUploadBehavior(settings) { @Override protected void renderScripts(final IHeaderResponse response) { super.renderScripts(response); response.render(JavaScriptHeaderItem.forReference( new JavaScriptResourceReference(SingleFileUploadBar.class, JQUERY_FILEUPLOAD_SINGLE_JS))); } @Override protected Map<String, Object> configureParameters(final Component component) { final Map<String, Object> variables = super.configureParameters(component); //the script to refresh page after sending file has been done variables.put("callbackRefreshScript", refreshAjaxBehavior.getCallbackScript()); variables.put("callbackFileOnChangeScript", onChangeAjaxBehavior.getCallbackScript()); onConfigureParameters(variables); return variables; } @Override protected void renderWidgetConfig(final IHeaderResponse response, final Map<String, Object> variables) { @SuppressWarnings("squid:S2095") PackageTextTemplate jsTmpl = new PackageTextTemplate(SingleFileUploadBar.class, CONFIG_JS); String s = jsTmpl.asString(variables); // call the configuration after all DOM elements are loaded response.render(OnDomReadyHeaderItem.forScript(s)); } }); } /** * This event is called when selecting a new file * @param target */ protected void onChange(final AjaxRequestTarget target) { } /** * Override this method to insert more variables to the widget configuration * * @param variables */ protected void onConfigureParameters(final Map<String, Object> variables) { } }
package com.atguigu.gmall.ums.controller; import java.util.Arrays; import java.util.Map; import com.atguigu.core.bean.PageVo; import com.atguigu.core.bean.QueryCondition; import com.atguigu.core.bean.Resp; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import com.atguigu.gmall.ums.entity.IntegrationChangeHistoryEntity; import com.atguigu.gmall.ums.service.IntegrationChangeHistoryService; /** * 积分变化历史记录 * * @author yangfuqi * @email 1654771175@qq.com * @date 2020-02-05 10:37:58 */ @Api(tags = "积分变化历史记录 管理") @RestController @RequestMapping("ums/integrationchangehistory") public class IntegrationChangeHistoryController { @Autowired private IntegrationChangeHistoryService integrationChangeHistoryService; /** * 列表 */ @ApiOperation("分页查询(排序)") @GetMapping("/list") @PreAuthorize("hasAuthority('ums:integrationchangehistory:list')") public Resp<PageVo> list(QueryCondition queryCondition) { PageVo page = integrationChangeHistoryService.queryPage(queryCondition); return Resp.ok(page); } /** * 信息 */ @ApiOperation("详情查询") @GetMapping("/info/{id}") @PreAuthorize("hasAuthority('ums:integrationchangehistory:info')") public Resp<IntegrationChangeHistoryEntity> info(@PathVariable("id") Long id){ IntegrationChangeHistoryEntity integrationChangeHistory = integrationChangeHistoryService.getById(id); return Resp.ok(integrationChangeHistory); } /** * 保存 */ @ApiOperation("保存") @PostMapping("/save") @PreAuthorize("hasAuthority('ums:integrationchangehistory:save')") public Resp<Object> save(@RequestBody IntegrationChangeHistoryEntity integrationChangeHistory){ integrationChangeHistoryService.save(integrationChangeHistory); return Resp.ok(null); } /** * 修改 */ @ApiOperation("修改") @PostMapping("/update") @PreAuthorize("hasAuthority('ums:integrationchangehistory:update')") public Resp<Object> update(@RequestBody IntegrationChangeHistoryEntity integrationChangeHistory){ integrationChangeHistoryService.updateById(integrationChangeHistory); return Resp.ok(null); } /** * 删除 */ @ApiOperation("删除") @PostMapping("/delete") @PreAuthorize("hasAuthority('ums:integrationchangehistory:delete')") public Resp<Object> delete(@RequestBody Long[] ids){ integrationChangeHistoryService.removeByIds(Arrays.asList(ids)); return Resp.ok(null); } }
/* * * Copyright (c) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for full license information. * */ package com.microsoft.msr.RiotEmulator; import com.microsoft.msr.DiceEmulator.DICE; import org.bouncycastle.asn1.*; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.X500NameBuilder; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.asn1.x509.*; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.io.pem.PemObject; import org.bouncycastle.util.io.pem.PemObjectGenerator; import org.bouncycastle.util.io.pem.PemWriter; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import java.security.*; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.ECGenParameterSpec; import java.text.ParseException; import java.text.SimpleDateFormat; public class RIoT { // Algs/Crypto parameters /** * The RIoT Emulator DRBG */ private static String rDRBG = "SHA1PRNG"; /** * The ECC curve to use (NIST P-256) */ private static String rEcCurve = "P-256"; /** * The signing algorithm to use */ private static String rSignAlg = "ECDSA"; /** * The signature scheme */ private static String rSigSch = "SHA256withECDSA"; /** * The full signature scheme */ private static ASN1ObjectIdentifier rSignatureOID = X9ObjectIdentifiers.ecdsa_with_SHA256; // Simulated input(s) /** * Simulated RIoT Core "measurement" */ private static byte[] rDigest = hstoba("b5859493661e2eae9677c55d590b9294e094abafd740787e050dfe6d859053a0"); /** * Seed for deterministic (and simulated) "root" CA signing key pair */ private static byte[] rR00t = hstoba("e3e7c713573fd9c8b8e1eaf453f1561502f071c05349c8dae626a90b1788e570"); // Certificates /** * Serial number for DeviceID Certificate */ private static byte[] rDevCertSerial = hstoba("0e0d0c0b0a"); /** * Serial number for DeviceID Certificate */ private static byte[] rAlisCertSerial = hstoba("0a0b0c0d0e"); // TODO: Create a container class for certificate info (and use one per cert) private static String rRootCertIssuerName = "RIoT R00t"; private static String rRootCertIssuerOrg = "MSR_TEST"; private static String rRootCertIssuerCountry = "US"; private static String rRootCertSubjectName = rRootCertIssuerName; // Self-signed private static String rRootCertSubjectOrg = rRootCertIssuerOrg; // Self-signed private static String rRootCertSubjectCountry = rRootCertIssuerCountry; // Self-signed private static String rDeviceCertIssuerName = rRootCertSubjectName; private static String rDeviceCertIssuerOrg = rRootCertSubjectOrg; private static String rDeviceCertIssuerCountry = rRootCertSubjectCountry; private static String rDeviceCertSubjectName = "RIoT Core"; private static String rDeviceCertSubjectOrg = "MSR_TEST"; private static String rDeviceCertSubjectCountry = "US"; private static String rAliasCertIssuerName = rDeviceCertSubjectName; private static String rAliasCertIssuerOrg = rDeviceCertSubjectOrg; private static String rAliasCertIssuerCountry = rDeviceCertSubjectCountry; private static String rAliasCertSubjectName = "RIoT Device"; private static String rAliasCertSubjectOrg = "MSR_TEST"; private static String rAliasCertSubjectCountry = "US"; /** * The OID for the DICE extension that encodes the DeviceID and FWID */ private static String rExtensionOID = "2.23.133.5.4.1"; /** * The path length constraint for the self-signed DeviceID certificate */ private static int rPathLenConstraint = 1; /** * Certificate validity period (start) */ private static String rValidityStart = "20170101000000 GMT"; /** * Certificate validity period (end) */ private static String rValidityEnd = "37011231235959 GMT"; // Public /** * Container for PEM-encoded keys and certificates created by the RIoT Emulator */ public static class DeviceAuthBundle { /** * Public portion of the "root" CA Key */ public PublicKey RootPublicKey; /** * PEM-encoded public portion of the "root" CA Key */ public String RootPublicKeyPem; /** * Private portion of the "root" CA Key */ public PrivateKey RootPrivateKey; /** * PEM-encoded private portion of the "root" CA Key */ public String RootPrivateKeyPem; /** * Self-signed "root" certificate */ public X509Certificate RootCert; /** * PEM-encoded self-signed "root" certificate */ public String RootCertPem; /** * Public portion of the DeviceID key */ public PublicKey DeviceIDPublic; /** * PEM-encoded public DeviceID key */ public String DeviceIDPublicPem; /** * Self-signed DeviceID certificate */ public X509Certificate DeviceIDCert; /** * PEM-encoded self-signed DeviceID certificate */ public String DeviceIDCertPem; /** * PEM-encoded self-signed Certificate Signing Request (CSR) for the * DeviceID (may be used to obtain a certificate from the device vendor PKI) */ public String DeviceIDCSR; /** * Public portion of the Alias Key */ public PublicKey AliasPublicKey; /** * PEM-encoded public portion of the Alias Key */ public String AliasPublicKeyPem; /** * Private portion of the Alias Key */ public PrivateKey AliasPrivateKey; /** * PEM-encoded private portion of the Alias Key */ public String AliasPrivateKeyPem; /** * Certificate signed by the DeviceID key encoding the public DeviceID and the FWID */ public X509Certificate AliasCert; /** * PEM-encoded certificate signed by the DeviceID key encoding the public * DeviceID and the FWID */ public String AliasCertPem; /** * Certificate signed by the "root" key for "proof of posession" */ public X509Certificate LeafCert; /** * PEM-encoded certificate signed signed by the "root" key for "proof of posession" */ public String LeafCertPem; } static { Security.addProvider(new BouncyCastleProvider()); } /** * Create a certificate proving possession of the root key. * * @param devAuth An initialized DeviceAuthBundle containing DICE/RIoT keys and certs * @param commonName The "verifier" string from the DPS to be inserted in the cert's TBS data */ public static void CreateLeafCert(DeviceAuthBundle devAuth, String commonName) { try { devAuth.LeafCert = RIoT.makeDeviceCert(devAuth, commonName); devAuth.LeafCertPem = dertopem("CERTIFICATE", devAuth.LeafCert.getEncoded()); } catch (Exception e) { e.printStackTrace(); return; } return; } /** * The RIoT Emulator. This takes a UDS value and a FWID and creates the resultant DeviceID and Alias * Keys and Certificates. * * @param UDS The Unique Device Secret for this emulated "device" * @param FWID The Firmware ID (e.g., the measurement of the firmware image) on this emulated "device" * @param createCSR Indicates whether a Certificate Signing Request should be generated * @param rCN String to provide as Subject Common Name in "root" CA Key Certificate * @param dCN String to provide as Subject Common Name in DeviceID Key Certificate * @param aCN String to provide as Subject Common Name in Alias Key Certificate * @return An instance of DeviceAuthBundle containing DeviceID and Alias Keys and Certificates */ public static DeviceAuthBundle CreateDeviceAuthBundle(byte[] UDS, byte[] FWID, boolean createCSR, String rCN, String dCN, String aCN) { rRootCertSubjectName = rRootCertIssuerName = rDeviceCertIssuerName = rCN; // Self-signed rDeviceCertSubjectName = rAliasCertIssuerName = dCN; rAliasCertSubjectName = aCN; return CreateDeviceAuthBundle(UDS, FWID, createCSR); } /** * The RIoT Emulator. This takes a UDS value and a FWID and creates the resultant DeviceID and Alias * Keys and Certificates. * * @param UDS The Unique Device Secret for this emulated "device" * @param FWID The Firmware ID (e.g., the measurement of the firmware image) on this emulated "device" * @param createCSR Indicates whether a Certificate Signing Request should be generated * @return An instance of DeviceAuthBundle containing DeviceID and Alias Keys and Certificates */ public static DeviceAuthBundle CreateDeviceAuthBundle(byte[] UDS, byte[] FWID, boolean createCSR) { if ((UDS.length != 32) || (FWID.length != 32)) { throw new IllegalArgumentException("UDS and FWID must be 32-bytes in length"); } try { DeviceAuthBundle authBundle = new DeviceAuthBundle(); /* Don't use UDS directly */ byte[] digest = DICE.DiceSHA256(UDS); /* Derive CDI based on UDS and RIoT Core "measurement" */ byte[] CDI = DICE.DiceSHA256(digest, rDigest); /* Don't use CDI directly */ digest = RIoT.Hash(CDI); /* Derive deterministic "root" CA key pair */ KeyPair rootKey = RIoT.DeriveEccKey(rR00t); /* Derive DeviceID key pair from CDI */ KeyPair devID = RIoT.DeriveEccKey(digest); /* Combine CDI and FWID, result in digest */ digest = RIoT.Hash(digest, FWID); /* Derive Alias Key pair from CDI and FWID */ KeyPair aliasKey = RIoT.DeriveEccKey(digest); /* Done with keys */ authBundle.RootPublicKey = rootKey.getPublic(); authBundle.RootPublicKeyPem = dertopem("PUBLIC KEY", rootKey.getPublic().getEncoded()); authBundle.RootPrivateKey = rootKey.getPrivate(); authBundle.RootPrivateKeyPem = dertopem("PRIVATE KEY", rootKey.getPrivate().getEncoded()); authBundle.DeviceIDPublic = devID.getPublic(); authBundle.DeviceIDPublicPem = dertopem("PUBLIC KEY", devID.getPublic().getEncoded()); authBundle.AliasPublicKey = aliasKey.getPublic(); authBundle.AliasPublicKeyPem = dertopem("PUBLIC KEY", aliasKey.getPublic().getEncoded()); authBundle.AliasPrivateKey = aliasKey.getPrivate(); authBundle.AliasPrivateKeyPem = dertopem("PRIVATE KEY", aliasKey.getPrivate().getEncoded()); /* Create the "root" CA certificate */ X509Certificate rootCert = RIoT.makeRootCert(rootKey); /* Create the DeviceID certificate */ X509Certificate devCert = RIoT.makeDeviceCert(rootKey, devID); /* Create the Alias Key certificate */ X509Certificate aliasCert = RIoT.makeAliasCert(devID, aliasKey, FWID); /* Done with Certificates */ authBundle.RootCert = rootCert; authBundle.RootCertPem = dertopem("CERTIFICATE", rootCert.getEncoded()); authBundle.DeviceIDCert = devCert; authBundle.DeviceIDCertPem = dertopem("CERTIFICATE", devCert.getEncoded()); authBundle.AliasCert = aliasCert; authBundle.AliasCertPem = dertopem("CERTIFICATE", aliasCert.getEncoded()); return authBundle; } catch (Exception e) { e.printStackTrace(); return null; } } private static X509Certificate makeRootCert(KeyPair rootKey) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, IOException, ParseException, SignatureException, CertificateException { SubjectPublicKeyInfo pubKeyInfo = SubjectPublicKeyInfo.getInstance(rootKey.getPublic().getEncoded()); X500NameBuilder issBldr = new X500NameBuilder(BCStyle.INSTANCE); issBldr.addRDN(BCStyle.CN,rRootCertIssuerName); issBldr.addRDN(BCStyle.O,rRootCertIssuerOrg); issBldr.addRDN(BCStyle.C,rRootCertIssuerCountry); X500Name issuer = issBldr.build(); X500NameBuilder subBldr = new X500NameBuilder(BCStyle.INSTANCE); subBldr.addRDN(BCStyle.CN,rRootCertSubjectName); subBldr.addRDN(BCStyle.O,rRootCertSubjectOrg); subBldr.addRDN(BCStyle.C,rRootCertSubjectCountry); X500Name subject = subBldr.build(); Signature sig = Signature.getInstance(rSigSch, BouncyCastleProvider.PROVIDER_NAME); SecureRandom seed = SecureRandom.getInstance(rDRBG); seed.setSeed(RIoT.Hash(rR00t)); // Deterministic seed, don't use directly sig.initSign(rootKey.getPrivate(), seed); Time vStart = new Time((new SimpleDateFormat("yyyymmddhhmmss Z")).parse(rValidityStart)); Time vEnd = new Time((new SimpleDateFormat("yyyymmddhhmmss Z")).parse(rValidityEnd)); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); /* Set certificate fields */ certGen.setSerialNumber(new ASN1Integer(hstoba("5A4B3C2D1E"))); certGen.setIssuer(issuer); certGen.setSubject(subject); certGen.setStartDate(vStart); certGen.setEndDate(vEnd); certGen.setSubjectPublicKeyInfo(pubKeyInfo); certGen.setSignature(new AlgorithmIdentifier(rSignatureOID)); /* Next, create extensions */ ExtensionsGenerator extGen = new ExtensionsGenerator(); extGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign)); extGen.addExtension(Extension.basicConstraints,true, new BasicConstraints(rPathLenConstraint + 1)); /* Set the extensions in the certificate */ certGen.setExtensions(extGen.generate()); /* Create the to-be-signed (TBS) certificate structure */ TBSCertificate tbsCert = certGen.generateTBSCertificate(); /* ...And sign it! (This is a self-signed cert) */ sig.update(tbsCert.getEncoded(ASN1Encoding.DER)); byte[] certSignature = sig.sign(); /* The final X509 certificate is the ASN.1 vector (tbsCert, sigAlg, certSignature) */ ASN1EncodableVector encVec = new ASN1EncodableVector(); encVec.add(tbsCert); encVec.add(new AlgorithmIdentifier(rSignatureOID)); encVec.add(new DERBitString(certSignature)); byte[] certDER = new DERSequence(encVec).getEncoded(ASN1Encoding.DER); /* Now, finally, make the X509 cert and return */ X509Certificate cert = (X509Certificate) CertificateFactory .getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME) .generateCertificate(new ByteArrayInputStream(certDER)); return cert; } // Used to create the leaf "verifier" cert private static X509Certificate makeDeviceCert(DeviceAuthBundle devAuth, String commonName) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, IOException, ParseException, SignatureException, CertificateException { KeyPair root = new KeyPair(devAuth.RootPublicKey, devAuth.RootPrivateKey); KeyPair devID = new KeyPair(devAuth.DeviceIDPublic, null); return makeDeviceCert(root, devID, commonName); } // Default Subject Common Name for DeviceID certificate private static X509Certificate makeDeviceCert(KeyPair rootKey, KeyPair deviceID) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, IOException, ParseException, SignatureException, CertificateException { return makeDeviceCert(rootKey, deviceID, rDeviceCertSubjectName); } // Create the DeviceID certificate private static X509Certificate makeDeviceCert(KeyPair rootKey, KeyPair deviceID, String commonName) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, IOException, ParseException, SignatureException, CertificateException { SubjectPublicKeyInfo pubKeyInfo = SubjectPublicKeyInfo.getInstance(deviceID.getPublic().getEncoded()); X500NameBuilder issBldr = new X500NameBuilder(BCStyle.INSTANCE); issBldr.addRDN(BCStyle.CN, rDeviceCertIssuerName); issBldr.addRDN(BCStyle.O, rDeviceCertIssuerOrg); issBldr.addRDN(BCStyle.C, rDeviceCertIssuerCountry); X500Name issuer = issBldr.build(); X500NameBuilder subBldr = new X500NameBuilder(BCStyle.INSTANCE); subBldr.addRDN(BCStyle.CN, commonName); subBldr.addRDN(BCStyle.O, rDeviceCertSubjectOrg); subBldr.addRDN(BCStyle.C, rDeviceCertSubjectCountry); X500Name subject = subBldr.build(); Signature sig = Signature.getInstance(rSigSch, BouncyCastleProvider.PROVIDER_NAME); SecureRandom seed = SecureRandom.getInstance(rDRBG); seed.setSeed(RIoT.Hash(rDeviceCertSubjectName.getBytes())); // Deterministic seed, don't use directly sig.initSign(rootKey.getPrivate(), seed); // TODO: This needs to change, see RNG comment in C-Emulator Time vStart = new Time((new SimpleDateFormat("yyyymmddhhmmss Z")).parse(rValidityStart)); Time vEnd = new Time((new SimpleDateFormat("yyyymmddhhmmss Z")).parse(rValidityEnd)); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); /* Set certificate fields */ certGen.setSerialNumber(new ASN1Integer(hstoba("0E0D0C0B0A"))); certGen.setIssuer(issuer); certGen.setSubject(subject); certGen.setStartDate(vStart); certGen.setEndDate(vEnd); certGen.setSubjectPublicKeyInfo(pubKeyInfo); certGen.setSignature(new AlgorithmIdentifier(rSignatureOID)); /* Next, create extensions */ ExtensionsGenerator extGen = new ExtensionsGenerator(); //extGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); extGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign)); extGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(rPathLenConstraint)); /* Set the extensions in the certificate */ certGen.setExtensions(extGen.generate()); /* Create the to-be-signed (TBS) certificate structure */ TBSCertificate tbsCert = certGen.generateTBSCertificate(); /* ...And sign it! (This is a self-signed cert) */ sig.update(tbsCert.getEncoded(ASN1Encoding.DER)); byte[] certSignature = sig.sign(); /* The final X509 certificate is the ASN.1 vector (tbsCert, sigAlg, certSignature) */ ASN1EncodableVector encVec = new ASN1EncodableVector(); encVec.add(tbsCert); encVec.add(new AlgorithmIdentifier(rSignatureOID)); encVec.add(new DERBitString(certSignature)); byte[] certDER = new DERSequence(encVec).getEncoded(ASN1Encoding.DER); /* Now, finally, make the X509 cert and return */ X509Certificate cert = (X509Certificate) CertificateFactory .getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME) .generateCertificate(new ByteArrayInputStream(certDER)); return cert; } private static X509Certificate makeAliasCert(KeyPair deviceID, KeyPair aliasKey, byte[] FWID) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, IOException, SignatureException, ParseException, CertificateException { SubjectPublicKeyInfo devicePub = SubjectPublicKeyInfo.getInstance(deviceID.getPublic().getEncoded()); SubjectPublicKeyInfo aliasPub = SubjectPublicKeyInfo.getInstance(aliasKey.getPublic().getEncoded()); X500NameBuilder issBldr = new X500NameBuilder(BCStyle.INSTANCE); issBldr.addRDN(BCStyle.CN, rAliasCertIssuerName); issBldr.addRDN(BCStyle.O, rAliasCertIssuerOrg); issBldr.addRDN(BCStyle.C, rAliasCertIssuerCountry); X500Name issuer = issBldr.build(); X500NameBuilder subBldr = new X500NameBuilder(BCStyle.INSTANCE); subBldr.addRDN(BCStyle.CN, rAliasCertSubjectName); subBldr.addRDN(BCStyle.O, rAliasCertSubjectOrg); subBldr.addRDN(BCStyle.C, rAliasCertSubjectCountry); X500Name subject = subBldr.build(); Signature sig = Signature.getInstance(rSigSch, BouncyCastleProvider.PROVIDER_NAME); SecureRandom seed = SecureRandom.getInstance(rDRBG); seed.setSeed(RIoT.Hash(FWID)); // Deterministic seed, don't use FWID directly sig.initSign(deviceID.getPrivate(), seed); // TODO: This needs to change, see RNG comment in C-Emulator Time vStart = new Time((new SimpleDateFormat("yyyymmddhhmmss Z")).parse(rValidityStart)); Time vEnd = new Time((new SimpleDateFormat("yyyymmddhhmmss Z")).parse(rValidityEnd)); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); /* Set certificate fields */ certGen.setSerialNumber(new ASN1Integer(rAlisCertSerial)); certGen.setIssuer(issuer); certGen.setSubject(subject); certGen.setStartDate(vStart); certGen.setEndDate(vEnd); certGen.setSubjectPublicKeyInfo(aliasPub); certGen.setSignature(new AlgorithmIdentifier(rSignatureOID)); /* Add the extensions */ ExtensionsGenerator extGen = new ExtensionsGenerator(); /* TLS client auth */ extGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); /* The full DeviceID public key and the FWID are encoded as Subject Alternative Name */ DERSequence riotExtension = getRiotExtension(FWID, deviceID); /* Add RIoT Extension */ extGen.addExtension(new ASN1ObjectIdentifier(rExtensionOID), false, riotExtension); //// wrapping to allow this name to be encoded in the OtherName field of a SAN //DERTaggedObject explicitEnvelope = new DERTaggedObject(false, 0, riotExtension); //DERSequence retSeq = new DERSequence(explicitEnvelope); // //extGen.addExtension(Extension.subjectAlternativeName, true, retSeq); /* Set the extensions in the certificate */ certGen.setExtensions(extGen.generate()); /* Create the to-be-signed (TBS) certificate structure */ TBSCertificate tbsCert = certGen.generateTBSCertificate(); /* ...And sign it! */ sig.update(tbsCert.getEncoded(ASN1Encoding.DER)); byte[] certSignature = sig.sign(); /* The final X509 certificate is the ASN.1 vector (tbsCert, sigAlg, certSignature) */ ASN1EncodableVector encVec = new ASN1EncodableVector(); encVec.add(tbsCert); encVec.add(new AlgorithmIdentifier(rSignatureOID)); encVec.add(new DERBitString(certSignature)); byte[] certDER = new DERSequence(encVec).getEncoded(ASN1Encoding.DER); /* Now, finally, make the X509 cert and return */ X509Certificate cert = (X509Certificate) CertificateFactory .getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME) .generateCertificate(new ByteArrayInputStream(certDER)); return cert; } /** * Create an ECC key pair deterministically based on the provided source data * * @param srcData The seed for key derivation * @return A new ECC key pair * @throws NoSuchAlgorithmException Problem with rSignAlg * @throws NoSuchProviderException Problem with BC provider * @throws InvalidAlgorithmParameterException Problem with rEcCurve */ public static KeyPair DeriveEccKey(byte[] srcData) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(rEcCurve); KeyPairGenerator ecGen = KeyPairGenerator.getInstance(rSignAlg, BouncyCastleProvider.PROVIDER_NAME); SecureRandom seed = SecureRandom.getInstance(rDRBG); seed.setSeed(srcData); // Deterministic seed value based on srcData ecGen.initialize(ecGenSpec, seed); KeyPair eccKP = ecGen.generateKeyPair(); return eccKP; } /** * Hashing function for RIoT emulation (SHA256) * * @param buf Byte buffer from which digest is computed * @return Digest of 'buf' * @throws NoSuchAlgorithmException When no "SHA-256" */ public static byte[] Hash(byte[] buf) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(buf); return md.digest(); } /** * Hash function for DICE emulation (SHA256) * * @param buf1 First byte buffer to be included in digest * @param buf2 Second byte buffer to be included in digest * @return Digest of 'buf1' and 'buf2' * @throws NoSuchAlgorithmException When no "SHA-256" */ public static byte[] Hash(byte[] buf1, byte[] buf2) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(buf1); md.update(buf2); return md.digest(); } private static DERSequence getRiotExtension(byte[] FWID, KeyPair deviceID) { /* The extension is constructed from the inside out */ SubjectPublicKeyInfo devicePubInfo = SubjectPublicKeyInfo.getInstance(deviceID.getPublic().getEncoded()); /* {hashAlgId, FWID Hash} */ DERSequence FWIDseq = new DERSequence(new ASN1Encodable[] { NISTObjectIdentifiers.id_sha256, new DEROctetString(FWID) }); /* {1, DeviceID, FWID} */ DERSequence EncodedDICEIdentity = new DERSequence(new ASN1Encodable[] { new ASN1Integer(1), // version devicePubInfo, FWIDseq }); //// {riotOid, encodedIdentity} //DERSequence TaggedEncodedID = new DERSequence(new ASN1Encodable[] // { // new ASN1ObjectIdentifier(rExtensionOID), // EncodedDICEIdentity // }); // return EncodedDICEIdentity; } /** * Convert DER encoded data to PEM with provided header * @param header The PEM header e.g., "PUBLIC KEY", "CERTIFICATE", etc. * @param derEncodedData DER-encoded byte array * @return PEM-encoded string * @throws IOException Error on writeObject/close */ private static String dertopem(String header, byte[] derEncodedData) throws IOException { PemObject obj = new PemObject(header, derEncodedData); StringWriter strWri = new StringWriter(); PemWriter pemWri = new PemWriter(strWri); pemWri.writeObject(obj); pemWri.close(); return strWri.toString(); } /** * Convert a hex string to an array of bytes * @param s Hex string to convert * @return Converted byte array */ private static byte[] hstoba(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)); } return data; } }
package com.azrul.echo.query; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
package com.lyd.mall.coupon.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.lyd.mall.coupon.entity.CouponEntity; import com.lyd.mall.coupon.service.CouponService; import com.lyd.common.utils.PageUtils; import com.lyd.common.utils.R; /** * 优惠券信息 * * @author liuyunda * @email man021436@163.com * @date 2020-12-28 23:56:22 */ @RefreshScope @RestController @RequestMapping("coupon/coupon") public class CouponController { @Autowired private CouponService couponService; @Value("${coupon.user.name}") private String name; @Value("${coupon.user.age}") private Integer age; /** * @Description: 测试配置中心 * @Param: [] * @return: com.lyd.common.utils.R * @Author: Liuyunda * @Date: 2020/12/29 */ @RequestMapping("/test") public R test(){ return R.ok().put("name",name).put("age",age); } /** * @Description: 获取优惠券信息 * @Param: [] * @return: com.lyd.common.utils.R * @Author: Liuyunda * @Date: 2020/12/29 */ @RequestMapping("/member/list") public R memberCoupons(){ CouponEntity couponEntity = new CouponEntity(); couponEntity.setCouponName("满100减10"); return R.ok().put("coupons",Arrays.asList(couponEntity)); } /** * 列表 */ @RequestMapping("/list") // @RequiresPermissions("coupon:coupon:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = couponService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") // @RequiresPermissions("coupon:coupon:info") public R info(@PathVariable("id") Long id){ CouponEntity coupon = couponService.getById(id); return R.ok().put("coupon", coupon); } /** * 保存 */ @RequestMapping("/save") // @RequiresPermissions("coupon:coupon:save") public R save(@RequestBody CouponEntity coupon){ couponService.save(coupon); return R.ok(); } /** * 修改 */ @RequestMapping("/update") // @RequiresPermissions("coupon:coupon:update") public R update(@RequestBody CouponEntity coupon){ couponService.updateById(coupon); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") // @RequiresPermissions("coupon:coupon:delete") public R delete(@RequestBody Long[] ids){ couponService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
package com.adeven.adjustio; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; // support multiple BroadcastReceivers for the INSTALL_REFERRER: // http://blog.appington.com/2012/08/01/giving-credit-for-android-app-installs public class ReferrerReceiver extends BroadcastReceiver { protected static final String REFERRER_KEY = "AdjustIoInstallReferrer"; @Override public void onReceive(Context context, Intent intent) { String rawReferrer = intent.getStringExtra("referrer"); if (rawReferrer == null) return; String referrer = ""; try { referrer = URLDecoder.decode(rawReferrer, "UTF-8"); } catch (UnsupportedEncodingException e) { referrer = "malformed"; } SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); preferences.edit().putString(REFERRER_KEY, referrer).commit(); } }
/* * The MIT License (MIT) * * Copyright 2021 Crown Copyright (Health Education England) * * 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 uk.nhs.hee.tis.trainee.sync.service; import static uk.nhs.hee.tis.trainee.sync.model.Operation.DELETE; import com.fasterxml.jackson.core.JsonProcessingException; import io.awspring.cloud.messaging.core.QueueMessagingTemplate; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import uk.nhs.hee.tis.trainee.sync.model.Post; import uk.nhs.hee.tis.trainee.sync.model.Record; import uk.nhs.hee.tis.trainee.sync.repository.PostRepository; @Slf4j @Service("tcs-Post") public class PostSyncService implements SyncService { private final PostRepository repository; private final DataRequestService dataRequestService; private final Set<String> requestedIds = new HashSet<>(); private final QueueMessagingTemplate messagingTemplate; private final String queueUrl; PostSyncService(PostRepository repository, DataRequestService dataRequestService, QueueMessagingTemplate messagingTemplate, @Value("${application.aws.sqs.post}") String queueUrl) { this.repository = repository; this.dataRequestService = dataRequestService; this.messagingTemplate = messagingTemplate; this.queueUrl = queueUrl; } @Override public void syncRecord(Record post) { if (!(post instanceof Post)) { String message = String.format("Invalid record type '%s'.", post.getClass()); throw new IllegalArgumentException(message); } // Send incoming post records to the post queue to be processed. messagingTemplate.convertAndSend(queueUrl, post); } /** * Synchronize the given post. * * @param post The post to synchronize. */ public void syncPost(Post post) { if (post.getOperation().equals(DELETE)) { repository.deleteById(post.getTisId()); } else { repository.save(post); } String id = post.getTisId(); requestedIds.remove(id); } public Optional<Post> findById(String id) { return repository.findById(id); } public Set<Post> findByEmployingBodyId(String trustId) { return repository.findByEmployingBodyId(trustId); } public Set<Post> findByTrainingBodyId(String trustId) { return repository.findByTrainingBodyId(trustId); } /** * Make a request to retrieve a specific post. * * @param id The id of the post to be retrieved. */ public void request(String id) { if (!requestedIds.contains(id)) { log.info("Sending request for Post [{}]", id); try { dataRequestService.sendRequest(Post.ENTITY_NAME, Map.of("id", id)); requestedIds.add(id); } catch (JsonProcessingException e) { log.error("Error while trying to request a Post", e); } } else { log.debug("Already requested Post [{}].", id); } } }
package com.novoda.demo.optionaldependencies; import android.widget.TextView; public class BaseOptionalDependencies { public void updatePaidContent(TextView textView) { // no-op } }
// 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.impala.catalog; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.ReentrantLock; import org.apache.hadoop.hive.common.StatsSetupConst; import org.apache.hadoop.hive.metastore.IMetaStoreClient; import org.apache.hadoop.hive.metastore.TableType; import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.impala.analysis.TableName; import org.apache.impala.common.ImpalaRuntimeException; import org.apache.impala.common.Pair; import org.apache.impala.thrift.TAccessLevel; import org.apache.impala.thrift.TCatalogObject; import org.apache.impala.thrift.TCatalogObjectType; import org.apache.impala.thrift.TColumn; import org.apache.impala.thrift.TColumnDescriptor; import org.apache.impala.thrift.TTable; import org.apache.impala.thrift.TTableDescriptor; import org.apache.impala.thrift.TTableStats; import org.apache.impala.util.HdfsCachingUtil; import org.apache.log4j.Logger; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * Base class for table metadata. * * This includes the concept of clustering columns, which are columns by which the table * data is physically clustered. In other words, if two rows share the same values * for the clustering columns, those two rows are most likely colocated. Note that this * is more general than Hive's CLUSTER BY ... INTO BUCKETS clause (which partitions * a key range into a fixed number of buckets). */ public abstract class Table implements CatalogObject { private static final Logger LOG = Logger.getLogger(Table.class); private long catalogVersion_ = Catalog.INITIAL_CATALOG_VERSION; protected org.apache.hadoop.hive.metastore.api.Table msTable_; protected final Db db_; protected final String name_; protected final String owner_; protected TAccessLevel accessLevel_ = TAccessLevel.READ_WRITE; // Lock protecting this table private final ReentrantLock tableLock_ = new ReentrantLock(); // Number of clustering columns. protected int numClusteringCols_; // estimated number of rows in table; -1: unknown. protected long numRows_ = -1; // colsByPos[i] refers to the ith column in the table. The first numClusteringCols are // the clustering columns. protected final ArrayList<Column> colsByPos_ = Lists.newArrayList(); // map from lowercase column name to Column object. private final Map<String, Column> colsByName_ = Maps.newHashMap(); // Type of this table (array of struct) that mirrors the columns. Useful for analysis. protected final ArrayType type_ = new ArrayType(new StructType()); // The lastDdlTime for this table; -1 if not set protected long lastDdlTime_; protected Table(org.apache.hadoop.hive.metastore.api.Table msTable, Db db, String name, String owner) { msTable_ = msTable; db_ = db; name_ = name.toLowerCase(); owner_ = owner; lastDdlTime_ = (msTable_ != null) ? CatalogServiceCatalog.getLastDdlTime(msTable_) : -1; } public ReentrantLock getLock() { return tableLock_; } public abstract TTableDescriptor toThriftDescriptor( int tableId, Set<Long> referencedPartitions); public abstract TCatalogObjectType getCatalogObjectType(); /** * Populate members of 'this' from metastore info. If 'reuseMetadata' is true, reuse * valid existing metadata. */ public abstract void load(boolean reuseMetadata, IMetaStoreClient client, org.apache.hadoop.hive.metastore.api.Table msTbl) throws TableLoadingException; public void addColumn(Column col) { colsByPos_.add(col); colsByName_.put(col.getName().toLowerCase(), col); ((StructType) type_.getItemType()).addField( new StructField(col.getName(), col.getType(), col.getComment())); } public void clearColumns() { colsByPos_.clear(); colsByName_.clear(); ((StructType) type_.getItemType()).clearFields(); } /** * Updates the lastDdlTime for this Table, if the new value is greater * than the existing value. Does nothing if the new value is less than * or equal to the existing value. */ public void updateLastDdlTime(long ddlTime) { // Ensure the lastDdlTime never goes backwards. if (ddlTime > lastDdlTime_) lastDdlTime_ = ddlTime; } // Returns a list of all column names for this table which we expect to have column // stats in the HMS. This exists because, when we request the column stats from HMS, // including a column name that does not have stats causes the // getTableColumnStatistics() to return nothing. For Hdfs tables, partition columns do // not have column stats in the HMS, but HBase table clustering columns do have column // stats. This method allows each table type to volunteer the set of columns we should // ask the metastore for in loadAllColumnStats(). protected List<String> getColumnNamesWithHmsStats() { List<String> ret = Lists.newArrayList(); for (String name: colsByName_.keySet()) ret.add(name); return ret; } /** * Loads column statistics for all columns in this table from the Hive metastore. Any * errors are logged and ignored, since the absence of column stats is not critical to * the correctness of the system. */ protected void loadAllColumnStats(IMetaStoreClient client) { if (LOG.isTraceEnabled()) LOG.trace("Loading column stats for table: " + name_); List<ColumnStatisticsObj> colStats; // We need to only query those columns which may have stats; asking HMS for other // columns causes loadAllColumnStats() to return nothing. List<String> colNames = getColumnNamesWithHmsStats(); try { colStats = client.getTableColumnStatistics(db_.getName(), name_, colNames); } catch (Exception e) { LOG.warn("Could not load column statistics for: " + getFullName(), e); return; } for (ColumnStatisticsObj stats: colStats) { Column col = getColumn(stats.getColName()); Preconditions.checkNotNull(col); if (!ColumnStats.isSupportedColType(col.getType())) { LOG.warn(String.format("Statistics for %s, column %s are not supported as " + "column has type %s", getFullName(), col.getName(), col.getType())); continue; } if (!col.updateStats(stats.getStatsData())) { LOG.warn(String.format("Failed to load column stats for %s, column %s. Stats " + "may be incompatible with column type %s. Consider regenerating statistics " + "for %s.", getFullName(), col.getName(), col.getType(), getFullName())); continue; } } } /** * Returns the value of the ROW_COUNT constant, or -1 if not found. */ protected static long getRowCount(Map<String, String> parameters) { if (parameters == null) return -1; String numRowsStr = parameters.get(StatsSetupConst.ROW_COUNT); if (numRowsStr == null) return -1; try { return Long.valueOf(numRowsStr); } catch (NumberFormatException exc) { // ignore } return -1; } /** * Creates a table of the appropriate type based on the given hive.metastore.api.Table * object. */ public static Table fromMetastoreTable(Db db, org.apache.hadoop.hive.metastore.api.Table msTbl) { // Create a table of appropriate type Table table = null; if (TableType.valueOf(msTbl.getTableType()) == TableType.VIRTUAL_VIEW) { table = new View(msTbl, db, msTbl.getTableName(), msTbl.getOwner()); } else if (HBaseTable.isHBaseTable(msTbl)) { table = new HBaseTable(msTbl, db, msTbl.getTableName(), msTbl.getOwner()); } else if (KuduTable.isKuduTable(msTbl)) { table = new KuduTable(msTbl, db, msTbl.getTableName(), msTbl.getOwner()); } else if (DataSourceTable.isDataSourceTable(msTbl)) { // It's important to check if this is a DataSourceTable before HdfsTable because // DataSourceTables are still represented by HDFS tables in the metastore but // have a special table property to indicate that Impala should use an external // data source. table = new DataSourceTable(msTbl, db, msTbl.getTableName(), msTbl.getOwner()); } else if (HdfsFileFormat.isHdfsInputFormatClass(msTbl.getSd().getInputFormat())) { table = new HdfsTable(msTbl, db, msTbl.getTableName(), msTbl.getOwner()); } return table; } /** * Factory method that creates a new Table from its Thrift representation. * Determines the type of table to create based on the Thrift table provided. */ public static Table fromThrift(Db parentDb, TTable thriftTable) throws TableLoadingException { Table newTable; if (!thriftTable.isSetLoad_status() && thriftTable.isSetMetastore_table()) { newTable = Table.fromMetastoreTable(parentDb, thriftTable.getMetastore_table()); } else { newTable = IncompleteTable.createUninitializedTable(parentDb, thriftTable.getTbl_name()); } newTable.loadFromThrift(thriftTable); newTable.validate(); return newTable; } public boolean isClusteringColumn(Column c) { return c.getPosition() < numClusteringCols_; } protected void loadFromThrift(TTable thriftTable) throws TableLoadingException { List<TColumn> columns = new ArrayList<TColumn>(); columns.addAll(thriftTable.getClustering_columns()); columns.addAll(thriftTable.getColumns()); colsByPos_.clear(); colsByPos_.ensureCapacity(columns.size()); try { for (int i = 0; i < columns.size(); ++i) { Column col = Column.fromThrift(columns.get(i)); colsByPos_.add(col.getPosition(), col); colsByName_.put(col.getName().toLowerCase(), col); ((StructType) type_.getItemType()).addField( new StructField(col.getName(), col.getType(), col.getComment())); } } catch (ImpalaRuntimeException e) { throw new TableLoadingException(String.format("Error loading schema for " + "table '%s'", getName()), e); } numClusteringCols_ = thriftTable.getClustering_columns().size(); // Estimated number of rows numRows_ = thriftTable.isSetTable_stats() ? thriftTable.getTable_stats().getNum_rows() : -1; // Default to READ_WRITE access if the field is not set. accessLevel_ = thriftTable.isSetAccess_level() ? thriftTable.getAccess_level() : TAccessLevel.READ_WRITE; } /** * Checks preconditions for this table to function as expected. Currently only checks * that all entries in colsByName_ use lower case keys. */ public void validate() throws TableLoadingException { for (String colName: colsByName_.keySet()) { if (!colName.equals(colName.toLowerCase())) { throw new TableLoadingException( "Expected lower case column name but found: " + colName); } } } /** * Must be called with 'tableLock_' held to protect against concurrent modifications * while producing the TTable result. */ public TTable toThrift() { // It would be simple to acquire and release the lock in this function. // However, in most cases toThrift() is called after modifying a table for which // the table lock should already be held, and we want the toThrift() to be consistent // with the modification. So this check helps us identify places where the lock // acquisition is probably missing entirely. if (!tableLock_.isHeldByCurrentThread()) { throw new IllegalStateException( "Table.toThrift() called without holding the table lock: " + getFullName() + " " + getClass().getName()); } TTable table = new TTable(db_.getName(), name_); table.setAccess_level(accessLevel_); // Populate both regular columns and clustering columns (if there are any). table.setColumns(new ArrayList<TColumn>()); table.setClustering_columns(new ArrayList<TColumn>()); for (int i = 0; i < colsByPos_.size(); ++i) { TColumn colDesc = colsByPos_.get(i).toThrift(); // Clustering columns come first. if (i < numClusteringCols_) { table.addToClustering_columns(colDesc); } else { table.addToColumns(colDesc); } } table.setMetastore_table(getMetaStoreTable()); if (numRows_ != -1) { table.setTable_stats(new TTableStats()); table.getTable_stats().setNum_rows(numRows_); } return table; } public TCatalogObject toTCatalogObject() { TCatalogObject catalogObject = new TCatalogObject(); catalogObject.setType(getCatalogObjectType()); catalogObject.setCatalog_version(getCatalogVersion()); catalogObject.setTable(toThrift()); return catalogObject; } /** * Gets the ColumnType from the given FieldSchema by using Impala's SqlParser. * Throws a TableLoadingException if the FieldSchema could not be parsed. * The type can either be: * - Supported by Impala, in which case the type is returned. * - A type Impala understands but is not yet implemented (e.g. date), the type is * returned but type.IsSupported() returns false. * - A supported type that exceeds an Impala limit, e.g., on the nesting depth. * - A type Impala can't understand at all, and a TableLoadingException is thrown. */ protected Type parseColumnType(FieldSchema fs) throws TableLoadingException { Type type = Type.parseColumnType(fs.getType()); if (type == null) { throw new TableLoadingException(String.format( "Unsupported type '%s' in column '%s' of table '%s'", fs.getType(), fs.getName(), getName())); } if (type.exceedsMaxNestingDepth()) { throw new TableLoadingException(String.format( "Type exceeds the maximum nesting depth of %s:\n%s", Type.MAX_NESTING_DEPTH, type.toSql())); } return type; } public Db getDb() { return db_; } public String getName() { return name_; } public String getFullName() { return (db_ != null ? db_.getName() + "." : "") + name_; } public TableName getTableName() { return new TableName(db_ != null ? db_.getName() : null, name_); } public ArrayList<Column> getColumns() { return colsByPos_; } /** * Returns a list of the column names ordered by position. */ public List<String> getColumnNames() { List<String> colNames = Lists.<String>newArrayList(); for (Column col: colsByPos_) { colNames.add(col.getName()); } return colNames; } /** * Returns a list of thrift column descriptors ordered by position. */ public List<TColumnDescriptor> getTColumnDescriptors() { List<TColumnDescriptor> colDescs = Lists.<TColumnDescriptor>newArrayList(); for (Column col: colsByPos_) { colDescs.add(new TColumnDescriptor(col.getName(), col.getType().toThrift())); } return colDescs; } /** * Subclasses should override this if they provide a storage handler class. Currently * only HBase tables need to provide a storage handler. */ public String getStorageHandlerClassName() { return null; } /** * Returns the list of all columns, but with partition columns at the end of * the list rather than the beginning. This is equivalent to the order in * which Hive enumerates columns. */ public ArrayList<Column> getColumnsInHiveOrder() { ArrayList<Column> columns = Lists.newArrayList(getNonClusteringColumns()); columns.addAll(getClusteringColumns()); return columns; } /** * Returns a struct type with the columns in the same order as getColumnsInHiveOrder(). */ public StructType getHiveColumnsAsStruct() { ArrayList<StructField> fields = Lists.newArrayListWithCapacity(colsByPos_.size()); for (Column col: getColumnsInHiveOrder()) { fields.add(new StructField(col.getName(), col.getType(), col.getComment())); } return new StructType(fields); } /** * Returns the list of all partition columns. */ public List<Column> getClusteringColumns() { return colsByPos_.subList(0, numClusteringCols_); } /** * Returns the list of all columns excluding any partition columns. */ public List<Column> getNonClusteringColumns() { return colsByPos_.subList(numClusteringCols_, colsByPos_.size()); } /** * Case-insensitive lookup. */ public Column getColumn(String name) { return colsByName_.get(name.toLowerCase()); } /** * Returns the metastore.api.Table object this Table was created from. Returns null * if the derived Table object was not created from a metastore Table (ex. InlineViews). */ public org.apache.hadoop.hive.metastore.api.Table getMetaStoreTable() { return msTable_; } public void setMetaStoreTable(org.apache.hadoop.hive.metastore.api.Table msTbl) { msTable_ = msTbl; } public int getNumClusteringCols() { return numClusteringCols_; } public long getNumRows() { return numRows_; } public ArrayType getType() { return type_; } @Override public long getCatalogVersion() { return catalogVersion_; } @Override public void setCatalogVersion(long catalogVersion) { catalogVersion_ = catalogVersion; } @Override public boolean isLoaded() { return true; } public static boolean isExternalTable( org.apache.hadoop.hive.metastore.api.Table msTbl) { return msTbl.getTableType().equalsIgnoreCase(TableType.EXTERNAL_TABLE.toString()); } /** * If the table is cached, it returns a <cache pool name, replication factor> pair * and adds the table cached directive ID to 'cacheDirIds'. Otherwise, it * returns a <null, 0> pair. */ public Pair<String, Short> getTableCacheInfo(List<Long> cacheDirIds) { String cachePoolName = null; Short cacheReplication = 0; Long cacheDirId = HdfsCachingUtil.getCacheDirectiveId(msTable_.getParameters()); if (cacheDirId != null) { try { cachePoolName = HdfsCachingUtil.getCachePool(cacheDirId); cacheReplication = HdfsCachingUtil.getCacheReplication(cacheDirId); Preconditions.checkNotNull(cacheReplication); if (numClusteringCols_ == 0) cacheDirIds.add(cacheDirId); } catch (ImpalaRuntimeException e) { // Catch the error so that the actual update to the catalog can progress, // this resets caching for the table though LOG.error( String.format("Cache directive %d was not found, uncache the table %s " + "to remove this message.", cacheDirId, getFullName())); cacheDirId = null; } } return new Pair<String, Short>(cachePoolName, cacheReplication); } }
/* * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.lexmodelbuilding.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum SlotConstraint { Required("Required"), Optional("Optional"); private String value; private SlotConstraint(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return SlotConstraint corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static SlotConstraint fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (SlotConstraint enumEntry : SlotConstraint.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
package io.ray.runtime; import com.google.common.base.Preconditions; import com.google.gson.Gson; import io.ray.api.BaseActorHandle; import io.ray.api.id.ActorId; import io.ray.api.id.JobId; import io.ray.api.id.UniqueId; import io.ray.api.runtimecontext.ResourceValue; import io.ray.runtime.config.RayConfig; import io.ray.runtime.context.NativeWorkerContext; import io.ray.runtime.exception.RayIntentionalSystemExitException; import io.ray.runtime.gcs.GcsClient; import io.ray.runtime.gcs.GcsClientOptions; import io.ray.runtime.generated.Common.RuntimeEnv; import io.ray.runtime.generated.Common.WorkerType; import io.ray.runtime.generated.Gcs.GcsNodeInfo; import io.ray.runtime.generated.Gcs.JobConfig; import io.ray.runtime.object.NativeObjectStore; import io.ray.runtime.runner.RunManager; import io.ray.runtime.task.NativeTaskExecutor; import io.ray.runtime.task.NativeTaskSubmitter; import io.ray.runtime.task.TaskExecutor; import io.ray.runtime.util.BinaryFileUtil; import io.ray.runtime.util.JniUtils; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Native runtime for cluster mode. */ public final class RayNativeRuntime extends AbstractRayRuntime { private static final Logger LOGGER = LoggerFactory.getLogger(RayNativeRuntime.class); private boolean startRayHead = false; /** * In Java, GC runs in a standalone thread, and we can't control the exact timing of garbage * collection. By using this lock, when {@link NativeObjectStore#nativeRemoveLocalReference} is * executing, the core worker will not be shut down, therefore it guarantees some kind of * thread-safety. Note that this guarantee only works for driver. */ private final ReadWriteLock shutdownLock = new ReentrantReadWriteLock(); public RayNativeRuntime(RayConfig rayConfig) { super(rayConfig); } private void updateSessionDir(GcsClient gcsClient) { // Fetch session dir from GCS. final String sessionDir = gcsClient.getInternalKV("session_dir"); Preconditions.checkNotNull(sessionDir); rayConfig.setSessionDir(sessionDir); } @Override public void start() { try { if (rayConfig.workerMode == WorkerType.DRIVER && rayConfig.getRedisAddress() == null) { // Set it to true before `RunManager.startRayHead` so `Ray.shutdown()` can still kill // Ray processes even if `Ray.init()` failed. startRayHead = true; RunManager.startRayHead(rayConfig); } Preconditions.checkNotNull(rayConfig.getRedisAddress()); // In order to remove redis dependency in Java lang, we use a temp dir to load library // instead of getting session dir from redis. if (rayConfig.workerMode == WorkerType.DRIVER) { String tmpDir = "/tmp/ray/".concat(String.valueOf(System.currentTimeMillis())); JniUtils.loadLibrary(tmpDir, BinaryFileUtil.CORE_WORKER_JAVA_LIBRARY, true); gcsClient = new GcsClient(rayConfig.getRedisAddress(), rayConfig.redisPassword); updateSessionDir(gcsClient); Preconditions.checkNotNull(rayConfig.sessionDir); } else { // Expose ray ABI symbols which may be depended by other shared // libraries such as libstreaming_java.so. // See BUILD.bazel:libcore_worker_library_java.so Preconditions.checkNotNull(rayConfig.sessionDir); JniUtils.loadLibrary(rayConfig.sessionDir, BinaryFileUtil.CORE_WORKER_JAVA_LIBRARY, true); gcsClient = new GcsClient(rayConfig.getRedisAddress(), rayConfig.redisPassword); } gcsClient = new GcsClient(rayConfig.getRedisAddress(), rayConfig.redisPassword); if (rayConfig.workerMode == WorkerType.DRIVER) { GcsNodeInfo nodeInfo = gcsClient.getNodeToConnectForDriver(rayConfig.nodeIp); rayConfig.rayletSocketName = nodeInfo.getRayletSocketName(); rayConfig.objectStoreSocketName = nodeInfo.getObjectStoreSocketName(); rayConfig.nodeManagerPort = nodeInfo.getNodeManagerPort(); } if (rayConfig.getJobId() == JobId.NIL) { rayConfig.setJobId(gcsClient.nextJobId()); } int numWorkersPerProcess = rayConfig.workerMode == WorkerType.DRIVER ? 1 : rayConfig.numWorkersPerProcess; byte[] serializedJobConfig = null; if (rayConfig.workerMode == WorkerType.DRIVER) { JobConfig.Builder jobConfigBuilder = JobConfig.newBuilder() .setNumJavaWorkersPerProcess(rayConfig.numWorkersPerProcess) .addAllJvmOptions(rayConfig.jvmOptionsForJavaWorker) .addAllCodeSearchPath(rayConfig.codeSearchPath); RuntimeEnv.Builder runtimeEnvBuilder = RuntimeEnv.newBuilder(); if (!rayConfig.workerEnv.isEmpty()) { // TODO(SongGuyang): Suppport complete runtime env interface for users. // Set worker env to the serialized runtime env json. Gson gson = new Gson(); Map<String, Map<String, String>> runtimeEnv = new HashMap<>(); runtimeEnv.put("env_vars", rayConfig.workerEnv); String gsonString = gson.toJson(runtimeEnv); runtimeEnvBuilder.setSerializedRuntimeEnv(gsonString); } else { runtimeEnvBuilder.setSerializedRuntimeEnv("{}"); } jobConfigBuilder.setRuntimeEnv(runtimeEnvBuilder.build()); serializedJobConfig = jobConfigBuilder.build().toByteArray(); } nativeInitialize( rayConfig.workerMode.getNumber(), rayConfig.nodeIp, rayConfig.getNodeManagerPort(), rayConfig.workerMode == WorkerType.DRIVER ? System.getProperty("user.dir") : "", rayConfig.objectStoreSocketName, rayConfig.rayletSocketName, (rayConfig.workerMode == WorkerType.DRIVER ? rayConfig.getJobId() : JobId.NIL).getBytes(), new GcsClientOptions(rayConfig), numWorkersPerProcess, rayConfig.logDir, serializedJobConfig, rayConfig.getStartupToken()); taskExecutor = new NativeTaskExecutor(this); workerContext = new NativeWorkerContext(); objectStore = new NativeObjectStore(workerContext, shutdownLock); taskSubmitter = new NativeTaskSubmitter(); LOGGER.debug( "RayNativeRuntime started with store {}, raylet {}", rayConfig.objectStoreSocketName, rayConfig.rayletSocketName); } catch (Exception e) { if (startRayHead) { try { RunManager.stopRay(); } catch (Exception e2) { // Ignore } } throw e; } } @Override public void shutdown() { // `shutdown` won't be called concurrently, but the lock is also used in `NativeObjectStore`. // When an object is garbage collected, the object will be unregistered from core worker. // Since GC runs in a separate thread, we need to make sure that core worker is available // when `NativeObjectStore` is accessing core worker in the GC thread. Lock writeLock = shutdownLock.writeLock(); writeLock.lock(); try { if (rayConfig.workerMode == WorkerType.DRIVER) { nativeShutdown(); if (startRayHead) { startRayHead = false; RunManager.stopRay(); } } if (null != gcsClient) { gcsClient.destroy(); gcsClient = null; } LOGGER.debug("RayNativeRuntime shutdown"); } finally { writeLock.unlock(); } } @SuppressWarnings("unchecked") @Override public <T extends BaseActorHandle> Optional<T> getActor(String name, boolean global) { if (name.isEmpty()) { return Optional.empty(); } byte[] actorIdBytes = nativeGetActorIdOfNamedActor(name, global); ActorId actorId = ActorId.fromBytes(actorIdBytes); if (actorId.isNil()) { return Optional.empty(); } else { return Optional.of((T) getActorHandle(actorId)); } } @Override public void killActor(BaseActorHandle actor, boolean noRestart) { nativeKillActor(actor.getId().getBytes(), noRestart); } @Override public Object getAsyncContext() { return new AsyncContext( workerContext.getCurrentWorkerId(), workerContext.getCurrentClassLoader()); } @Override public void setAsyncContext(Object asyncContext) { nativeSetCoreWorker(((AsyncContext) asyncContext).workerId.getBytes()); workerContext.setCurrentClassLoader(((AsyncContext) asyncContext).currentClassLoader); super.setAsyncContext(asyncContext); } @Override public void exitActor() { if (rayConfig.workerMode != WorkerType.WORKER || runtimeContext.getCurrentActorId().isNil()) { throw new RuntimeException("This shouldn't be called on a non-actor worker."); } LOGGER.info("Actor {} is exiting.", runtimeContext.getCurrentActorId()); throw new RayIntentionalSystemExitException( String.format("Actor %s is exiting.", runtimeContext.getCurrentActorId())); } @Override public void run() { Preconditions.checkState(rayConfig.workerMode == WorkerType.WORKER); nativeRunTaskExecutor(taskExecutor); } @Override public Map<String, List<ResourceValue>> getAvailableResourceIds() { return nativeGetResourceIds(); } private static native void nativeInitialize( int workerMode, String ndoeIpAddress, int nodeManagerPort, String driverName, String storeSocket, String rayletSocket, byte[] jobId, GcsClientOptions gcsClientOptions, int numWorkersPerProcess, String logDir, byte[] serializedJobConfig, int startupToken); private static native void nativeRunTaskExecutor(TaskExecutor taskExecutor); private static native void nativeShutdown(); private static native void nativeKillActor(byte[] actorId, boolean noRestart); private static native byte[] nativeGetActorIdOfNamedActor(String actorName, boolean global); private static native void nativeSetCoreWorker(byte[] workerId); private static native Map<String, List<ResourceValue>> nativeGetResourceIds(); static class AsyncContext { public final UniqueId workerId; public final ClassLoader currentClassLoader; AsyncContext(UniqueId workerId, ClassLoader currentClassLoader) { this.workerId = workerId; this.currentClassLoader = currentClassLoader; } } }
package es.ucm.fdi.iw.utils; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import es.ucm.fdi.iw.constants.Constants; import es.ucm.fdi.iw.constants.ConstantsPdfFile; import es.ucm.fdi.iw.model.Answer; import es.ucm.fdi.iw.model.Contest; import es.ucm.fdi.iw.model.Question; /** * Processes a JSON file and creates a new contest * @author aitorcay */ public class ContestFileReader { private static final Logger log = LogManager.getLogger(ContestFileReader.class); /** * Procesa la información de un fichero JSON y crea una nueva prueba * * @param jsonContest contenido del fichero JSON * @return prueba creada con la información procesada */ public static Contest readContestFile(String jsonContest) { Contest contest = new Contest(); try { JSONObject jContest = new JSONObject(jsonContest); contest.setName(jContest.getString(Constants.NOMBRE_CONCURSO)); contest.setEnabled((byte) 0); contest.setComplete((byte) 0); contest.setChecked((byte)0); JSONArray jQuestionsList = jContest.getJSONArray(Constants.PREGUNTAS); JSONObject jQuestion; List<Question> questionList = new ArrayList<>(); List<Answer> answerList; JSONArray answerInput; String[] answerData; Question question; Answer answer; Answer empty; for (int i = 0; i < jQuestionsList.length(); i++) { jQuestion = jQuestionsList.getJSONObject(i); question = new Question(); question.setText(jQuestion.getString(Constants.ENUNCIADO)); question.setContest(contest); answerList = new ArrayList<>(); empty = new Answer(); empty.setQuestion(question); empty.setText(Constants.NO_ANSWER); empty.setScore(0); answerList.add(empty); answerInput = jQuestion.getJSONArray(Constants.RESPUESTAS); for(int j = 0; j < answerInput.length(); j++) { answerData = answerInput.getString(j).split(Constants.SEPARATOR); log.info(answerInput); answer = new Answer(); answer.setQuestion(question); answer.setText(answerData[0]); answer.setScore(Double.parseDouble(answerData[1])); answerList.add(answer); } question.setAnswers(answerList); questionList.add(question); } contest.setQuestions(questionList); log.info("Concurso cargado con éxito:\n{}", contest); } catch (JSONException e) { log.warn("Error durante el procesado. Por favor revisa el fichero", e); } return contest; } }
/* * Copyright (c) 2021 Airbyte, Inc., all rights reserved. */ package io.airbyte.workers.temporal.sync; import io.airbyte.commons.json.Jsons; import io.airbyte.config.OperatorDbtInput; import io.airbyte.scheduler.models.IntegrationLauncherConfig; import io.airbyte.scheduler.models.JobRunConfig; import io.airbyte.workers.WorkerApp; import io.airbyte.workers.WorkerConfigs; import java.util.Map; import java.util.UUID; public class DbtLauncherWorker extends LauncherWorker<OperatorDbtInput, Void> { public static final String DBT = "dbt-orchestrator"; private static final String POD_NAME_PREFIX = "orchestrator-dbt"; public static final String INIT_FILE_DESTINATION_LAUNCHER_CONFIG = "destinationLauncherConfig.json"; public DbtLauncherWorker(final UUID connectionId, final IntegrationLauncherConfig destinationLauncherConfig, final JobRunConfig jobRunConfig, final WorkerConfigs workerConfigs, final WorkerApp.ContainerOrchestratorConfig containerOrchestratorConfig) { super( connectionId, DBT, POD_NAME_PREFIX, jobRunConfig, Map.of( INIT_FILE_DESTINATION_LAUNCHER_CONFIG, Jsons.serialize(destinationLauncherConfig)), containerOrchestratorConfig, workerConfigs.getResourceRequirements(), Void.class); } }
package com.revolsys.util.count; import org.jeometry.common.logging.Logs; import com.revolsys.util.Counter; public abstract class AbstractLabelCounters implements LabelCounters { private boolean logCounts = true; protected String message; private int providerCount = 0; public AbstractLabelCounters() { super(); } @Override public synchronized void addCountsText(final StringBuilder sb) { int totalCount = 0; if (this.message != null) { sb.append(this.message); } sb.append("\n"); for (final String label : getLabels()) { sb.append(label); sb.append("\t"); final Counter counter = getCounter(label); final long count = counter.get(); totalCount += count; sb.append(count); sb.append("\n"); } sb.append("Total"); sb.append("\t"); sb.append(totalCount); sb.append("\n"); } @Override public synchronized void connect() { this.providerCount++; } @Override public synchronized void disconnect() { this.providerCount--; if (this.providerCount <= 0) { logCounts(); } } @Override public String getMessage() { return this.message; } @Override public boolean isLogCounts() { return this.logCounts; } @Override public synchronized String logCounts() { final StringBuilder sb = new StringBuilder(); addCountsText(sb); final String string = sb.toString(); if (isLogCounts() && !isEmpty()) { Logs.info(this, string); } return string; } @Override public void setLogCounts(final boolean logCounts) { this.logCounts = logCounts; } @Override public void setMessage(final String message) { this.message = message; } @Override public String toString() { return this.message; } }
// Template Source: IBaseMethodRequestBuilder.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.requests.extensions; import com.microsoft.graph.requests.extensions.IWorkbookChartPointCountRequest; import com.microsoft.graph.http.IRequestBuilder; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The interface for the Workbook Chart Point Count Request Builder. */ public interface IWorkbookChartPointCountRequestBuilder extends IRequestBuilder { /** * Creates the IWorkbookChartPointCountRequest * * @param requestOptions the options for the request * @return the IWorkbookChartPointCountRequest instance */ IWorkbookChartPointCountRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions); /** * Creates the IWorkbookChartPointCountRequest with specific options instead of the existing options * * @param requestOptions the options for the request * @return the IWorkbookChartPointCountRequest instance */ IWorkbookChartPointCountRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions); }
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/context.proto package com.google.api; public interface ContextOrBuilder extends // @@protoc_insertion_point(interface_extends:google.api.Context) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * A list of RPC context rules that apply to individual API methods. * **NOTE:** All service configuration rules follow "last one wins" order. * </pre> * * <code>repeated .google.api.ContextRule rules = 1;</code> */ java.util.List<com.google.api.ContextRule> getRulesList(); /** * * * <pre> * A list of RPC context rules that apply to individual API methods. * **NOTE:** All service configuration rules follow "last one wins" order. * </pre> * * <code>repeated .google.api.ContextRule rules = 1;</code> */ com.google.api.ContextRule getRules(int index); /** * * * <pre> * A list of RPC context rules that apply to individual API methods. * **NOTE:** All service configuration rules follow "last one wins" order. * </pre> * * <code>repeated .google.api.ContextRule rules = 1;</code> */ int getRulesCount(); /** * * * <pre> * A list of RPC context rules that apply to individual API methods. * **NOTE:** All service configuration rules follow "last one wins" order. * </pre> * * <code>repeated .google.api.ContextRule rules = 1;</code> */ java.util.List<? extends com.google.api.ContextRuleOrBuilder> getRulesOrBuilderList(); /** * * * <pre> * A list of RPC context rules that apply to individual API methods. * **NOTE:** All service configuration rules follow "last one wins" order. * </pre> * * <code>repeated .google.api.ContextRule rules = 1;</code> */ com.google.api.ContextRuleOrBuilder getRulesOrBuilder(int index); }
package com.showka.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import lombok.Getter; import lombok.Setter; /** * 取消売上(計上済みだが、計上を取り消した売上) * */ @Entity @Table(name = "c_uriage") @Getter @Setter public class CUriage extends EntityBase implements Serializable { /** SID. */ private static final long serialVersionUID = 1l; /** 売上ID */ @Id @Column(name = "uriage_id", nullable = false, length = 255) private String uriageId; /** 売上. */ @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "uriage_id", referencedColumnName = "record_id", insertable = false, updatable = false) private TUriage uriage; }
/** * Copyright (C) 2010-2016 eBusiness Information, Excilys Group * Copyright (C) 2016-2020 the AndroidAnnotations 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 org.androidannotations.holder; import static com.helger.jcodemodel.JExpr._new; import static com.helger.jcodemodel.JExpr._null; import static com.helger.jcodemodel.JExpr._super; import static com.helger.jcodemodel.JExpr._this; import static com.helger.jcodemodel.JExpr.cast; import static com.helger.jcodemodel.JExpr.invoke; import static com.helger.jcodemodel.JMod.PRIVATE; import static com.helger.jcodemodel.JMod.PUBLIC; import static org.androidannotations.helper.ModelConstants.generationSuffix; import java.util.ArrayList; import java.util.List; import javax.lang.model.element.TypeElement; import org.androidannotations.AndroidAnnotationsEnvironment; import org.androidannotations.helper.AndroidManifest; import org.androidannotations.helper.AnnotationHelper; import org.androidannotations.helper.CanonicalNameConstants; import org.androidannotations.holder.ReceiverRegistrationDelegate.IntentFilterData; import org.androidannotations.internal.core.helper.ActivityIntentBuilder; import org.androidannotations.internal.core.helper.IntentBuilder; import com.helger.jcodemodel.AbstractJClass; import com.helger.jcodemodel.AbstractJType; import com.helger.jcodemodel.IJAssignmentTarget; import com.helger.jcodemodel.IJExpression; import com.helger.jcodemodel.JBlock; import com.helger.jcodemodel.JClassAlreadyExistsException; import com.helger.jcodemodel.JDefinedClass; import com.helger.jcodemodel.JExpr; import com.helger.jcodemodel.JFieldRef; import com.helger.jcodemodel.JFieldVar; import com.helger.jcodemodel.JInvocation; import com.helger.jcodemodel.JMethod; import com.helger.jcodemodel.JMod; import com.helger.jcodemodel.JVar; public class EActivityHolder extends EComponentWithViewSupportHolder implements HasIntentBuilder, HasExtras, HasInstanceState, HasOptionsMenu, HasOnActivityResult, HasActivityLifecycleMethods, HasReceiverRegistration, HasPreferenceHeaders { private ActivityIntentBuilder intentBuilder; private JMethod onCreate; private JMethod setIntent; private JMethod setContentViewLayout; private JVar initSavedInstanceParam; private JDefinedClass intentBuilderClass; private InstanceStateDelegate instanceStateDelegate; private OnActivityResultDelegate onActivityResultDelegate; private ReceiverRegistrationDelegate<EActivityHolder> receiverRegistrationDelegate; private PreferenceActivityDelegate preferencesHolder; private JMethod injectExtrasMethod; private JBlock injectExtrasBlock; private JVar injectExtras; private JBlock onCreateOptionsMenuMethodBody; private JBlock onCreateOptionsMenuMethodInflateBody; private JVar onCreateOptionsMenuMenuInflaterVar; private JVar onCreateOptionsMenuMenuParam; private JVar onOptionsItemSelectedItem; private JVar onOptionsItemSelectedItemId; private JBlock onOptionsItemSelectedMiddleBlock; private NonConfigurationHolder nonConfigurationHolder; private JBlock initIfNonConfigurationNotNullBlock; private JVar initNonConfigurationInstance; private JMethod getLastNonConfigurationInstance; private JBlock onRetainNonConfigurationInstanceBindBlock; private JVar onRetainNonConfigurationInstance; private JBlock onStartBeforeSuperBlock; private JBlock onStartAfterSuperBlock; private JBlock onRestartBeforeSuperBlock; private JBlock onRestartAfterSuperBlock; private JBlock onResumeBeforeSuperBlock; private JBlock onResumeAfterSuperBlock; private JBlock onPauseBeforeSuperBlock; private JBlock onPauseAfterSuperBlock; private JMethod onStopMethod; private JBlock onStopBeforeSuperBlock; private JMethod onDestroyMethod; private JBlock onDestroyBeforeSuperBlock; private JBlock onDestroyAfterSuperBlock; private JMethod onNewIntentMethod; private JBlock onNewIntentAfterSuperBlock; private JBlock onConfigurationChangedBeforeSuperBlock; private JBlock onConfigurationChangedAfterSuperBlock; private JVar onConfigurationChangedNewConfigParam; private JMethod onContentChanged; private JBlock onContentChangedAfterSuperBlock; public EActivityHolder(AndroidAnnotationsEnvironment environment, TypeElement annotatedElement, AndroidManifest androidManifest) throws Exception { super(environment, annotatedElement); instanceStateDelegate = new InstanceStateDelegate(this); onActivityResultDelegate = new OnActivityResultDelegate(this); receiverRegistrationDelegate = new ReceiverRegistrationDelegate<>(this); preferencesHolder = new PreferenceActivityDelegate(this); setSetContentView(); intentBuilder = new ActivityIntentBuilder(this, androidManifest); intentBuilder.build(); implementBeanHolder(); } @Override protected void setContextRef() { contextRef = _this(); } @Override protected void setInit() { init = generatedClass.method(PRIVATE, getCodeModel().VOID, "init" + generationSuffix()); AbstractJClass bundleClass = getClasses().BUNDLE; initSavedInstanceParam = init.param(bundleClass, "savedInstanceState"); getOnCreate(); } public JMethod getOnCreate() { if (onCreate == null) { setOnCreate(); } return onCreate; } public JMethod getSetIntent() { if (setIntent == null) { setSetIntent(); } return setIntent; } private void setOnCreate() { onCreate = generatedClass.method(PUBLIC, getCodeModel().VOID, "onCreate"); onCreate.annotate(Override.class); AbstractJClass bundleClass = getClasses().BUNDLE; JVar onCreateSavedInstanceState = onCreate.param(bundleClass, "savedInstanceState"); JBlock onCreateBody = onCreate.body(); JVar previousNotifier = viewNotifierHelper.replacePreviousNotifier(onCreateBody); onCreateBody.invoke(getInit()).arg(onCreateSavedInstanceState); onCreateBody.invoke(_super(), onCreate).arg(onCreateSavedInstanceState); viewNotifierHelper.resetPreviousNotifier(onCreateBody, previousNotifier); } // CHECKSTYLE:OFF private void setOnStart() { JMethod method = generatedClass.method(JMod.PUBLIC, getCodeModel().VOID, "onStart"); method.annotate(Override.class); JBlock body = method.body(); onStartBeforeSuperBlock = body.blockSimple(); body.invoke(_super(), method); onStartAfterSuperBlock = body.blockSimple(); } public JBlock getOnRestartAfterSuperBlock() { if (onRestartAfterSuperBlock == null) { setOnRestart(); } return onRestartAfterSuperBlock; } private void setOnRestart() { JMethod method = generatedClass.method(JMod.PUBLIC, getCodeModel().VOID, "onRestart"); method.annotate(Override.class); JBlock body = method.body(); onRestartBeforeSuperBlock = body.blockSimple(); body.invoke(_super(), method); onRestartAfterSuperBlock = body.blockSimple(); } private void setOnResume() { JMethod method = generatedClass.method(JMod.PUBLIC, getCodeModel().VOID, "onResume"); method.annotate(Override.class); JBlock body = method.body(); onResumeBeforeSuperBlock = body.blockSimple(); body.invoke(_super(), method); onResumeAfterSuperBlock = body.blockSimple(); } private void setOnPause() { JMethod method = generatedClass.method(JMod.PUBLIC, getCodeModel().VOID, "onPause"); method.annotate(Override.class); JBlock body = method.body(); onPauseBeforeSuperBlock = body.blockSimple(); body.invoke(_super(), method); onPauseAfterSuperBlock = body.blockSimple(); } private void setOnNewIntent() { onNewIntentMethod = generatedClass.method(JMod.PUBLIC, getCodeModel().VOID, "onNewIntent"); onNewIntentMethod.annotate(Override.class); JVar intent = onNewIntentMethod.param(getClasses().INTENT, "intent"); JBlock body = onNewIntentMethod.body(); body.invoke(_super(), onNewIntentMethod).arg(intent); onNewIntentAfterSuperBlock = body.blockSimple(); } private void setSetIntent() { setIntent = generatedClass.method(PUBLIC, getCodeModel().VOID, "setIntent"); setIntent.annotate(Override.class); JVar methodParam = setIntent.param(getClasses().INTENT, "newIntent"); JBlock setIntentBody = setIntent.body(); setIntentBody.invoke(_super(), setIntent).arg(methodParam); } public JMethod getOnStop() { if (onStopMethod == null) { setOnStop(); } return onStopMethod; } private void setOnStop() { onStopMethod = generatedClass.method(JMod.PUBLIC, getCodeModel().VOID, "onStop"); onStopMethod.annotate(Override.class); JBlock body = onStopMethod.body(); onStopBeforeSuperBlock = body.blockSimple(); body.invoke(_super(), onStopMethod); } public JMethod getOnDestroy() { if (onDestroyMethod == null) { setOnDestroy(); } return onDestroyMethod; } private void setOnDestroy() { onDestroyMethod = generatedClass.method(JMod.PUBLIC, getCodeModel().VOID, "onDestroy"); onDestroyMethod.annotate(Override.class); JBlock body = onDestroyMethod.body(); onDestroyBeforeSuperBlock = body.blockSimple(); body.invoke(_super(), onDestroyMethod); onDestroyAfterSuperBlock = body.blockSimple(); } public JBlock getOnConfigurationChangedBeforeSuperBlock() { if (onConfigurationChangedBeforeSuperBlock == null) { setOnConfigurationChanged(); } return onConfigurationChangedBeforeSuperBlock; } public JBlock getOnConfigurationChangedAfterSuperBlock() { if (onConfigurationChangedAfterSuperBlock == null) { setOnConfigurationChanged(); } return onConfigurationChangedAfterSuperBlock; } public JVar getOnConfigurationChangedNewConfigParam() { if (onConfigurationChangedNewConfigParam == null) { setOnConfigurationChanged(); } return onConfigurationChangedNewConfigParam; } private void setOnConfigurationChanged() { JMethod method = generatedClass.method(JMod.PUBLIC, getCodeModel().VOID, "onConfigurationChanged"); method.annotate(Override.class); AbstractJClass configurationClass = getClasses().CONFIGURATION; onConfigurationChangedNewConfigParam = method.param(configurationClass, "newConfig"); JBlock body = method.body(); onConfigurationChangedBeforeSuperBlock = body.blockSimple(); body.invoke(_super(), method).arg(onConfigurationChangedNewConfigParam); onConfigurationChangedAfterSuperBlock = body.blockSimple(); } public JMethod getOnContentChanged() { if (onContentChanged == null) { setOnContentChanged(); } return onContentChanged; } public JBlock getOnContentChangedAfterSuperBlock() { if (onContentChangedAfterSuperBlock == null) { setOnContentChanged(); } return onContentChangedAfterSuperBlock; } private void setOnContentChanged() { onContentChanged = generatedClass.method(JMod.PUBLIC, getCodeModel().VOID, "onContentChanged"); onContentChanged.annotate(Override.class); JBlock body = onContentChanged.body(); body.invoke(_super(), onContentChanged); onContentChangedAfterSuperBlock = body.blockSimple(); } private void setOnCreateOptionsMenu() { JMethod method = generatedClass.method(PUBLIC, getCodeModel().BOOLEAN, "onCreateOptionsMenu"); method.annotate(Override.class); JBlock methodBody = method.body(); onCreateOptionsMenuMenuParam = method.param(getClasses().MENU, "menu"); onCreateOptionsMenuMenuInflaterVar = methodBody.decl(getClasses().MENU_INFLATER, "menuInflater", invoke("getMenuInflater")); onCreateOptionsMenuMethodInflateBody = methodBody.blockSimple(); onCreateOptionsMenuMethodBody = methodBody.blockSimple(); methodBody._return(_super().invoke(method).arg(onCreateOptionsMenuMenuParam)); } private void setOnOptionsItemSelected() { JMethod method = generatedClass.method(JMod.PUBLIC, getCodeModel().BOOLEAN, "onOptionsItemSelected"); method.annotate(Override.class); JBlock methodBody = method.body(); onOptionsItemSelectedItem = method.param(getClasses().MENU_ITEM, "item"); onOptionsItemSelectedItemId = methodBody.decl(getCodeModel().INT, "itemId_", onOptionsItemSelectedItem.invoke("getItemId")); onOptionsItemSelectedMiddleBlock = methodBody.blockSimple(); methodBody._return(invoke(_super(), method).arg(onOptionsItemSelectedItem)); } @Override protected void setFindNativeFragmentById() { JMethod method = generatedClass.method(PRIVATE, getClasses().FRAGMENT, "findNativeFragmentById"); JVar idParam = method.param(getCodeModel().INT, "id"); JBlock body = method.body(); body._return(invoke("getFragmentManager").invoke("findFragmentById").arg(idParam)); findNativeFragmentById = method; } @Override protected void setFindSupportFragmentById() { JMethod method; if (getProcessingEnvironment().getElementUtils().getTypeElement(CanonicalNameConstants.ANDROIDX_FRAGMENT) == null) { method = getGeneratedClass().method(PRIVATE, getClasses().SUPPORT_V4_FRAGMENT, "findSupportFragmentById"); } else { method = getGeneratedClass().method(PRIVATE, getClasses().ANDROIDX_FRAGMENT, "findSupportFragmentById"); } JVar idParam = method.param(getCodeModel().INT, "id"); JBlock body = method.body(); body._return(invoke("getSupportFragmentManager").invoke("findFragmentById").arg(idParam)); findSupportFragmentById = method; } @Override protected void setFindNativeFragmentByTag() { JMethod method = generatedClass.method(PRIVATE, getClasses().FRAGMENT, "findNativeFragmentByTag"); JVar tagParam = method.param(getClasses().STRING, "tag"); JBlock body = method.body(); body._return(invoke("getFragmentManager").invoke("findFragmentByTag").arg(tagParam)); findNativeFragmentByTag = method; } @Override protected void setFindSupportFragmentByTag() { JMethod method; if (getProcessingEnvironment().getElementUtils().getTypeElement(CanonicalNameConstants.ANDROIDX_FRAGMENT) == null) { method = getGeneratedClass().method(PRIVATE, getClasses().SUPPORT_V4_FRAGMENT, "findSupportFragmentByTag"); } else { method = getGeneratedClass().method(PRIVATE, getClasses().ANDROIDX_FRAGMENT, "findSupportFragmentByTag"); } JVar tagParam = method.param(getClasses().STRING, "tag"); JBlock body = method.body(); body._return(invoke("getSupportFragmentManager").invoke("findFragmentByTag").arg(tagParam)); findSupportFragmentByTag = method; } public JMethod getSetContentViewLayout() { if (setContentViewLayout == null) { setSetContentView(); } return setContentViewLayout; } private void setSetContentView() { getOnCreate(); AbstractJClass layoutParamsClass = getClasses().VIEW_GROUP_LAYOUT_PARAMS; setContentViewLayout = setContentViewMethod(new AbstractJType[] { getCodeModel().INT }, new String[] { "layoutResID" }); setContentViewMethod(new AbstractJType[] { getClasses().VIEW, layoutParamsClass }, new String[] { "view", "params" }); setContentViewMethod(new AbstractJType[] { getClasses().VIEW }, new String[] { "view" }); } private JMethod setContentViewMethod(AbstractJType[] paramTypes, String[] paramNames) { JMethod method = generatedClass.method(JMod.PUBLIC, getCodeModel().VOID, "setContentView"); method.annotate(Override.class); List<JVar> params = new ArrayList<>(); for (int i = 0; i < paramTypes.length; i++) { JVar param = method.param(paramTypes[i], paramNames[i]); params.add(param); } JBlock body = method.body(); JInvocation superCall = body.invoke(JExpr._super(), method); for (JVar arg : params) { superCall.arg(arg); } viewNotifierHelper.invokeViewChanged(body); return method; } @Override public IJExpression getFindViewByIdExpression(JVar idParam) { return JExpr._this().invoke("findViewById").arg(idParam); } public JVar getInitSavedInstanceParam() { return initSavedInstanceParam; } @Override public IntentBuilder getIntentBuilder() { return intentBuilder; } @Override public void setIntentBuilderClass(JDefinedClass intentBuilderClass) { this.intentBuilderClass = intentBuilderClass; } @Override public JDefinedClass getIntentBuilderClass() { return intentBuilderClass; } // CHECKSTYLE:ON @Override public JMethod getInjectExtrasMethod() { if (injectExtrasMethod == null) { setInjectExtras(); } return injectExtrasMethod; } @Override public JBlock getInjectExtrasBlock() { if (injectExtrasBlock == null) { setInjectExtras(); } return injectExtrasBlock; } @Override public JVar getInjectExtras() { if (injectExtras == null) { setInjectExtras(); } return injectExtras; } private void setInjectExtras() { injectExtrasMethod = generatedClass.method(PRIVATE, getCodeModel().VOID, "injectExtras" + generationSuffix()); JBlock injectExtrasBody = injectExtrasMethod.body(); injectExtras = injectExtrasBody.decl(getClasses().BUNDLE, "extras_", invoke("getIntent").invoke("getExtras")); injectExtrasBlock = injectExtrasBody._if(injectExtras.ne(_null()))._then(); getSetIntent().body().invoke(injectExtrasMethod); getInitBodyInjectionBlock().invoke(injectExtrasMethod); } public JBlock getOnNewIntentAfterSuperBlock() { if (onNewIntentAfterSuperBlock == null) { setOnNewIntent(); } return onNewIntentAfterSuperBlock; } @Override public JBlock getSaveStateMethodBody() { return instanceStateDelegate.getSaveStateMethodBody(); } @Override public JVar getSaveStateBundleParam() { return instanceStateDelegate.getSaveStateBundleParam(); } @Override public JMethod getRestoreStateMethod() { return instanceStateDelegate.getRestoreStateMethod(); } @Override public JBlock getRestoreStateMethodBody() { return instanceStateDelegate.getRestoreStateMethodBody(); } @Override public JVar getRestoreStateBundleParam() { return instanceStateDelegate.getRestoreStateBundleParam(); } @Override public JBlock getOnCreateOptionsMenuMethodBody() { if (onCreateOptionsMenuMethodBody == null) { setOnCreateOptionsMenu(); } return onCreateOptionsMenuMethodBody; } @Override public JBlock getOnCreateOptionsMenuMethodInflateBody() { if (onCreateOptionsMenuMethodInflateBody == null) { setOnCreateOptionsMenu(); } return onCreateOptionsMenuMethodInflateBody; } @Override public JVar getOnCreateOptionsMenuMenuInflaterVar() { if (onCreateOptionsMenuMenuInflaterVar == null) { setOnCreateOptionsMenu(); } return onCreateOptionsMenuMenuInflaterVar; } @Override public JVar getOnCreateOptionsMenuMenuParam() { if (onCreateOptionsMenuMenuParam == null) { setOnCreateOptionsMenu(); } return onCreateOptionsMenuMenuParam; } @Override public JVar getOnOptionsItemSelectedItem() { if (onOptionsItemSelectedItem == null) { setOnOptionsItemSelected(); } return onOptionsItemSelectedItem; } @Override public JVar getOnOptionsItemSelectedItemId() { if (onOptionsItemSelectedItemId == null) { setOnOptionsItemSelected(); } return onOptionsItemSelectedItemId; } @Override public JBlock getOnOptionsItemSelectedMiddleBlock() { if (onOptionsItemSelectedMiddleBlock == null) { setOnOptionsItemSelected(); } return onOptionsItemSelectedMiddleBlock; } public NonConfigurationHolder getNonConfigurationHolder() throws JClassAlreadyExistsException { if (nonConfigurationHolder == null) { setNonConfigurationHolder(); } return nonConfigurationHolder; } private void setNonConfigurationHolder() throws JClassAlreadyExistsException { nonConfigurationHolder = new NonConfigurationHolder(this); } public JBlock getInitIfNonConfigurationNotNullBlock() throws JClassAlreadyExistsException { if (initIfNonConfigurationNotNullBlock == null) { setInitNonConfigurationInstance(); } return initIfNonConfigurationNotNullBlock; } public JVar getInitNonConfigurationInstance() throws JClassAlreadyExistsException { if (initNonConfigurationInstance == null) { setInitNonConfigurationInstance(); } return initNonConfigurationInstance; } private void setInitNonConfigurationInstance() throws JClassAlreadyExistsException { JBlock initBody = getInitBodyInjectionBlock(); JDefinedClass ncHolderClass = getNonConfigurationHolder().getGeneratedClass(); initNonConfigurationInstance = initBody.decl(ncHolderClass, "nonConfigurationInstance", cast(ncHolderClass, _super().invoke(getGetLastNonConfigurationInstance()))); initIfNonConfigurationNotNullBlock = initBody._if(initNonConfigurationInstance.ne(_null()))._then(); } public JMethod getGetLastNonConfigurationInstance() throws JClassAlreadyExistsException { if (getLastNonConfigurationInstance == null) { setGetLastNonConfigurationInstance(); } return getLastNonConfigurationInstance; } private void setGetLastNonConfigurationInstance() throws JClassAlreadyExistsException { AnnotationHelper annotationHelper = new AnnotationHelper(getEnvironment()); TypeElement fragmentActivityTypeElement = getFragmentActivity(annotationHelper); TypeElement typeElement = annotationHelper.typeElementFromQualifiedName(generatedClass._extends().fullName()); String getLastNonConfigurationInstanceName = "getLastNonConfigurationInstance"; if (fragmentActivityTypeElement != null && annotationHelper.isSubtype(typeElement.asType(), fragmentActivityTypeElement.asType())) { getLastNonConfigurationInstanceName = "getLastCustomNonConfigurationInstance"; } NonConfigurationHolder ncHolder = getNonConfigurationHolder(); JDefinedClass ncHolderClass = ncHolder.getGeneratedClass(); JFieldVar superNonConfigurationInstanceField = ncHolder.getSuperNonConfigurationInstanceField(); getLastNonConfigurationInstance = generatedClass.method(PUBLIC, Object.class, getLastNonConfigurationInstanceName); getLastNonConfigurationInstance.annotate(Override.class); JBlock body = getLastNonConfigurationInstance.body(); JVar nonConfigurationInstance = body.decl(ncHolderClass, "nonConfigurationInstance", cast(ncHolderClass, _super().invoke(getLastNonConfigurationInstance))); body._if(nonConfigurationInstance.eq(_null()))._then()._return(_null()); body._return(nonConfigurationInstance.ref(superNonConfigurationInstanceField)); } public JBlock getOnRetainNonConfigurationInstanceBindBlock() throws JClassAlreadyExistsException { if (onRetainNonConfigurationInstanceBindBlock == null) { setOnRetainNonConfigurationInstance(); } return onRetainNonConfigurationInstanceBindBlock; } public JVar getOnRetainNonConfigurationInstance() throws JClassAlreadyExistsException { if (onRetainNonConfigurationInstance == null) { setOnRetainNonConfigurationInstance(); } return onRetainNonConfigurationInstance; } private void setOnRetainNonConfigurationInstance() throws JClassAlreadyExistsException { AnnotationHelper annotationHelper = new AnnotationHelper(getEnvironment()); TypeElement fragmentActivityTypeElement = getFragmentActivity(annotationHelper); TypeElement typeElement = annotationHelper.typeElementFromQualifiedName(generatedClass._extends().fullName()); String onRetainNonConfigurationInstanceName = "onRetainNonConfigurationInstance"; if (fragmentActivityTypeElement != null && annotationHelper.isSubtype(typeElement.asType(), fragmentActivityTypeElement.asType())) { onRetainNonConfigurationInstanceName = "onRetainCustomNonConfigurationInstance"; } NonConfigurationHolder ncHolder = getNonConfigurationHolder(); JDefinedClass ncHolderClass = ncHolder.getGeneratedClass(); JMethod onRetainNonConfigurationInstanceMethod = generatedClass.method(PUBLIC, ncHolderClass, onRetainNonConfigurationInstanceName); onRetainNonConfigurationInstanceMethod.annotate(Override.class); JBlock methodBody = onRetainNonConfigurationInstanceMethod.body(); onRetainNonConfigurationInstance = methodBody.decl(ncHolderClass, "nonConfigurationInstanceState_", _new(ncHolderClass)); IJExpression superCall = _super().invoke(onRetainNonConfigurationInstanceMethod); methodBody.assign(onRetainNonConfigurationInstance.ref(ncHolder.getSuperNonConfigurationInstanceField()), superCall); onRetainNonConfigurationInstanceBindBlock = methodBody.blockSimple(); methodBody._return(onRetainNonConfigurationInstance); } private TypeElement getFragmentActivity(AnnotationHelper annotationHelper) { TypeElement supportFragmentActivity = annotationHelper.typeElementFromQualifiedName(CanonicalNameConstants.FRAGMENT_ACTIVITY); if (supportFragmentActivity == null) { return annotationHelper.typeElementFromQualifiedName(CanonicalNameConstants.ANDROIDX_FRAGMENT_ACTIVITY); } return supportFragmentActivity; } @Override public JBlock getOnActivityResultCaseBlock(int requestCode) { return onActivityResultDelegate.getCaseBlock(requestCode); } @Override public JVar getOnActivityResultDataParam() { return onActivityResultDelegate.getDataParam(); } @Override public JVar getOnActivityResultResultCodeParam() { return onActivityResultDelegate.getResultCodeParam(); } public JBlock getOnActivityResultAfterSuperBlock() { return onActivityResultDelegate.getAfterSuperBlock(); } public JVar getOnActivityResultRequestCodeParam() { return onActivityResultDelegate.getRequestCodeParam(); } @Override public JMethod getOnActivityResultMethod() { return onActivityResultDelegate.getMethod(); } public JBlock getOnDestroyAfterSuperBlock() { if (onDestroyAfterSuperBlock == null) { setOnDestroy(); } return onDestroyAfterSuperBlock; } @Override public JBlock getOnResumeAfterSuperBlock() { if (onResumeAfterSuperBlock == null) { setOnResume(); } return onResumeAfterSuperBlock; } @Override public JBlock getOnCreateAfterSuperBlock() { return getInitBody(); } @Override public JBlock getOnDestroyBeforeSuperBlock() { if (onDestroyBeforeSuperBlock == null) { setOnDestroy(); } return onDestroyBeforeSuperBlock; } @Override public JBlock getOnStartAfterSuperBlock() { if (onStartAfterSuperBlock == null) { setOnStart(); } return onStartAfterSuperBlock; } @Override public JBlock getOnStopBeforeSuperBlock() { if (onStopBeforeSuperBlock == null) { setOnStop(); } return onStopBeforeSuperBlock; } @Override public JBlock getOnPauseBeforeSuperBlock() { if (onPauseBeforeSuperBlock == null) { setOnPause(); } return onPauseBeforeSuperBlock; } public JBlock getOnPauseAfterSuperBlock() { if (onPauseAfterSuperBlock == null) { setOnPause(); } return onPauseAfterSuperBlock; } @Override public JBlock getStartLifecycleAfterSuperBlock() { return getOnCreateAfterSuperBlock(); } @Override public JBlock getEndLifecycleBeforeSuperBlock() { return getOnDestroyAfterSuperBlock(); } @Override public JFieldVar getIntentFilterField(IntentFilterData intentFilterData) { return receiverRegistrationDelegate.getIntentFilterField(intentFilterData); } @Override public JBlock getIntentFilterInitializationBlock(IntentFilterData intentFilterData) { return getInitBodyInjectionBlock(); } @Override public JBlock getPreferenceScreenInitializationBlock() { return getOnCreate().body(); } @Override public JBlock getAddPreferencesFromResourceInjectionBlock() { return preferencesHolder.getAddPreferencesFromResourceInjectionBlock(); } @Override public JBlock getAddPreferencesFromResourceAfterInjectionBlock() { return preferencesHolder.getAddPreferencesFromResourceAfterInjectionBlock(); } @Override public FoundPreferenceHolder getFoundPreferenceHolder(JFieldRef idRef, AbstractJClass preferenceClass) { return preferencesHolder.getFoundPreferenceHolder(idRef, preferenceClass); } @Override public FoundPreferenceHolder getFoundPreferenceHolder(JFieldRef idRef, AbstractJClass preferenceClass, IJAssignmentTarget fieldRef) { return preferencesHolder.getFoundPreferenceHolder(idRef, preferenceClass, fieldRef); } @Override public boolean usingSupportV7Preference() { return preferencesHolder.usingSupportV7Preference(); } @Override public boolean usingAndroidxPreference() { return preferencesHolder.usingAndroidxPreference(); } @Override public AbstractJClass getBasePreferenceClass() { return preferencesHolder.getBasePreferenceClass(); } @Override public JBlock getOnBuildHeadersBlock() { return preferencesHolder.getOnBuildHeadersBlock(); } @Override public JVar getOnBuildHeadersTargetParam() { return preferencesHolder.getOnBuildHeadersTargetParam(); } }
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.fincore.compliance.sign.list.apply response. * * @author auto create * @since 1.0, 2021-12-29 14:38:51 */ public class AlipayFincoreComplianceSignListApplyResponse extends AlipayResponse { private static final long serialVersionUID = 5674998622549485521L; /** * 业务请求单号 */ @ApiField("business_id") private String businessId; /** * 用印记录id */ @ApiField("file_code") private String fileCode; public void setBusinessId(String businessId) { this.businessId = businessId; } public String getBusinessId( ) { return this.businessId; } public void setFileCode(String fileCode) { this.fileCode = fileCode; } public String getFileCode( ) { return this.fileCode; } }
package com.Ray.pojo; import java.util.Date; public class Role { private Integer id; //id private String roleCode; //角色编码 private String roleName; //角色名称 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRoleCode() { return roleCode; } public void setRoleCode(String roleCode) { this.roleCode = roleCode; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } @Override public String toString() { return "Role{" + "id=" + id + ", roleCode='" + roleCode + '\'' + ", roleName='" + roleName + '\'' + '}'; } public Role() { } public Role(Integer id, String roleCode, String roleName) { this.id = id; this.roleCode = roleCode; this.roleName = roleName; } }
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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.appcutt.libs.pulltorefresh.internal; import android.view.View; /** * Interface that allows PullToRefreshBase to hijack the call to * AdapterView.setEmptyView() * * @author chris */ public interface EmptyViewMethodAccessor { /** * Calls upto AdapterView.setEmptyView() * * @param emptyView - to set as Empty View */ public void setEmptyViewInternal(View emptyView); /** * Should call PullToRefreshBase.setEmptyView() which will then * automatically call through to setEmptyViewInternal() * * @param emptyView - to set as Empty View */ public void setEmptyView(View emptyView); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.metastore; import java.io.IOException; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileChecksum; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.fs.Trash; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hive.metastore.api.Database; import org.apache.hadoop.hive.metastore.api.MetaException; import org.apache.hadoop.hive.metastore.conf.MetastoreConf; import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars; import org.apache.hadoop.hive.metastore.utils.FileUtils; import org.apache.hadoop.hive.metastore.utils.StringUtils; import org.apache.hadoop.security.UserGroupInformation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ReplChangeManager { private static final Logger LOG = LoggerFactory.getLogger(ReplChangeManager.class); static private ReplChangeManager instance; private static boolean inited = false; private static boolean enabled = false; private static Path cmroot; private static Configuration conf; private String msUser; private String msGroup; private static final String ORIG_LOC_TAG = "user.original-loc"; static final String REMAIN_IN_TRASH_TAG = "user.remain-in-trash"; private static final String URI_FRAGMENT_SEPARATOR = "#"; public static final String SOURCE_OF_REPLICATION = "repl.source.for"; public enum RecycleType { MOVE, COPY } public static class FileInfo { private FileSystem srcFs; private Path sourcePath; private Path cmPath; private String checkSum; private boolean useSourcePath; private String subDir; private boolean copyDone; public FileInfo(FileSystem srcFs, Path sourcePath, String subDir) { this(srcFs, sourcePath, null, null, true, subDir); } public FileInfo(FileSystem srcFs, Path sourcePath, Path cmPath, String checkSum, boolean useSourcePath, String subDir) { this.srcFs = srcFs; this.sourcePath = sourcePath; this.cmPath = cmPath; this.checkSum = checkSum; this.useSourcePath = useSourcePath; this.subDir = subDir; this.copyDone = false; } public FileSystem getSrcFs() { return srcFs; } public Path getSourcePath() { return sourcePath; } public Path getCmPath() { return cmPath; } public String getCheckSum() { return checkSum; } public boolean isUseSourcePath() { return useSourcePath; } public void setIsUseSourcePath(boolean useSourcePath) { this.useSourcePath = useSourcePath; } public String getSubDir() { return subDir; } public boolean isCopyDone() { return copyDone; } public void setCopyDone(boolean copyDone) { this.copyDone = copyDone; } public Path getEffectivePath() { if (useSourcePath) { return sourcePath; } else { return cmPath; } } } public static ReplChangeManager getInstance(Configuration conf) throws MetaException { if (instance == null) { instance = new ReplChangeManager(conf); } return instance; } private ReplChangeManager(Configuration conf) throws MetaException { try { if (!inited) { if (MetastoreConf.getBoolVar(conf, ConfVars.REPLCMENABLED)) { ReplChangeManager.enabled = true; ReplChangeManager.cmroot = new Path(MetastoreConf.getVar(conf, ConfVars.REPLCMDIR)); ReplChangeManager.conf = conf; FileSystem cmFs = cmroot.getFileSystem(conf); // Create cmroot with permission 700 if not exist if (!cmFs.exists(cmroot)) { cmFs.mkdirs(cmroot); cmFs.setPermission(cmroot, new FsPermission("700")); } UserGroupInformation usergroupInfo = UserGroupInformation.getCurrentUser(); msUser = usergroupInfo.getShortUserName(); msGroup = usergroupInfo.getPrimaryGroupName(); } inited = true; } } catch (IOException e) { throw new MetaException(StringUtils.stringifyException(e)); } } // Filter files starts with ".". Note Hadoop consider files starts with // "." or "_" as hidden file. However, we need to replicate files starts // with "_". We find at least 2 use cases: // 1. For har files, _index and _masterindex is required files // 2. _success file is required for Oozie to indicate availability of data source private static final PathFilter hiddenFileFilter = new PathFilter(){ public boolean accept(Path p){ return !p.getName().startsWith("."); } }; /*** * Move a path into cmroot. If the path is a directory (of a partition, or table if nonpartitioned), * recursively move files inside directory to cmroot. Note the table must be managed table * @param path a single file or directory * @param type if the files to be copied or moved to cmpath. * Copy is costly but preserve the source file * @param ifPurge if the file should skip Trash when move/delete source file. * This is referred only if type is MOVE. * @return int * @throws IOException */ public int recycle(Path path, RecycleType type, boolean ifPurge) throws IOException { if (!enabled) { return 0; } int count = 0; FileSystem fs = path.getFileSystem(conf); if (fs.isDirectory(path)) { FileStatus[] files = fs.listStatus(path, hiddenFileFilter); for (FileStatus file : files) { count += recycle(file.getPath(), type, ifPurge); } } else { String fileCheckSum = checksumFor(path, fs); Path cmPath = getCMPath(conf, path.getName(), fileCheckSum, cmroot.toString()); // set timestamp before moving to cmroot, so we can // avoid race condition CM remove the file before setting // timestamp long now = System.currentTimeMillis(); fs.setTimes(path, now, -1); boolean success = false; if (fs.exists(cmPath) && fileCheckSum.equalsIgnoreCase(checksumFor(cmPath, fs))) { // If already a file with same checksum exists in cmPath, just ignore the copy/move // Also, mark the operation is unsuccessful to notify that file with same name already // exist which will ensure the timestamp of cmPath is updated to avoid clean-up by // CM cleaner. success = false; } else { switch (type) { case MOVE: { LOG.info("Moving {} to {}", path.toString(), cmPath.toString()); // Rename fails if the file with same name already exist. success = fs.rename(path, cmPath); break; } case COPY: { LOG.info("Copying {} to {}", path.toString(), cmPath.toString()); // It is possible to have a file with same checksum in cmPath but the content is // partially copied or corrupted. In this case, just overwrite the existing file with // new one. success = FileUtils.copy(fs, path, fs, cmPath, false, true, conf); break; } default: // Operation fails as invalid input break; } } // Ignore if a file with same content already exist in cmroot // We might want to setXAttr for the new location in the future if (success) { // set the file owner to hive (or the id metastore run as) fs.setOwner(cmPath, msUser, msGroup); // tag the original file name so we know where the file comes from // Note we currently only track the last known trace as // xattr has limited capacity. We shall revisit and store all original // locations if orig-loc becomes important try { fs.setXAttr(cmPath, ORIG_LOC_TAG, path.toString().getBytes()); } catch (UnsupportedOperationException e) { LOG.warn("Error setting xattr for {}", path.toString()); } count++; } else { if (LOG.isDebugEnabled()) { LOG.debug("A file with the same content of {} already exists, ignore", path.toString()); } // Need to extend the tenancy if we saw a newer file with the same content fs.setTimes(cmPath, now, -1); } // Tag if we want to remain in trash after deletion. // If multiple files share the same content, then // any file claim remain in trash would be granted if ((type == RecycleType.MOVE) && !ifPurge) { try { fs.setXAttr(cmPath, REMAIN_IN_TRASH_TAG, new byte[] { 0 }); } catch (UnsupportedOperationException e) { LOG.warn("Error setting xattr for {}", cmPath.toString()); } } } return count; } // Get checksum of a file static public String checksumFor(Path path, FileSystem fs) throws IOException { // TODO: fs checksum only available on hdfs, need to // find a solution for other fs (eg, local fs, s3, etc) String checksumString = null; FileChecksum checksum = fs.getFileChecksum(path); if (checksum != null) { checksumString = StringUtils.byteToHexString( checksum.getBytes(), 0, checksum.getLength()); } return checksumString; } /*** * Convert a path of file inside a partition or table (if non-partitioned) * to a deterministic location of cmroot. So user can retrieve the file back * with the original location plus checksum. * @param conf Hive configuration * @param name original filename * @param checkSum checksum of the file, can be retrieved by {@link #checksumFor(Path, FileSystem)} * @param cmRootUri CM Root URI. (From remote source if REPL LOAD flow. From local config if recycle.) * @return Path */ static Path getCMPath(Configuration conf, String name, String checkSum, String cmRootUri) { String newFileName = name + "_" + checkSum; int maxLength = conf.getInt(DFSConfigKeys.DFS_NAMENODE_MAX_COMPONENT_LENGTH_KEY, DFSConfigKeys.DFS_NAMENODE_MAX_COMPONENT_LENGTH_DEFAULT); if (newFileName.length() > maxLength) { newFileName = newFileName.substring(0, maxLength-1); } return new Path(cmRootUri, newFileName); } /*** * Get original file specified by src and chksumString. If the file exists and checksum * matches, return the file; otherwise, use chksumString to retrieve it from cmroot * @param src Original file location * @param checksumString Checksum of the original file * @param srcCMRootURI CM root URI of the source cluster * @param subDir Sub directory to which the source file belongs to * @param conf Hive configuration * @return Corresponding FileInfo object */ public static FileInfo getFileInfo(Path src, String checksumString, String srcCMRootURI, String subDir, Configuration conf) throws MetaException { try { FileSystem srcFs = src.getFileSystem(conf); if (checksumString == null) { return new FileInfo(srcFs, src, subDir); } Path cmPath = getCMPath(conf, src.getName(), checksumString, srcCMRootURI); if (!srcFs.exists(src)) { return new FileInfo(srcFs, src, cmPath, checksumString, false, subDir); } String currentChecksumString; try { currentChecksumString = checksumFor(src, srcFs); } catch (IOException ex) { // If the file is missing or getting modified, then refer CM path return new FileInfo(srcFs, src, cmPath, checksumString, false, subDir); } if ((currentChecksumString == null) || checksumString.equals(currentChecksumString)) { return new FileInfo(srcFs, src, cmPath, checksumString, true, subDir); } else { return new FileInfo(srcFs, src, cmPath, checksumString, false, subDir); } } catch (IOException e) { throw new MetaException(StringUtils.stringifyException(e)); } } /*** * Concatenate filename, checksum, source cmroot uri and subdirectory with "#" * @param fileUriStr Filename string * @param fileChecksum Checksum string * @param encodedSubDir sub directory path into which this file belongs to. Here encoded means, * the multiple levels of subdirectories are concatenated with path separator "/" * @return Concatenated Uri string */ // TODO: this needs to be enhanced once change management based filesystem is implemented // Currently using fileuri#checksum#cmrooturi#subdirs as the format public static String encodeFileUri(String fileUriStr, String fileChecksum, String encodedSubDir) throws IOException { String encodedUri = fileUriStr; if ((fileChecksum != null) && (cmroot != null)) { encodedUri = encodedUri + URI_FRAGMENT_SEPARATOR + fileChecksum + URI_FRAGMENT_SEPARATOR + FileUtils.makeQualified(cmroot, conf); } else { encodedUri = encodedUri + URI_FRAGMENT_SEPARATOR + URI_FRAGMENT_SEPARATOR; } encodedUri = encodedUri + URI_FRAGMENT_SEPARATOR + ((encodedSubDir != null) ? encodedSubDir : ""); if (LOG.isDebugEnabled()) { LOG.debug("Encoded URI: " + encodedUri); } return encodedUri; } /*** * Split uri with fragment into file uri, subdirs, checksum and source cmroot uri. * Currently using fileuri#checksum#cmrooturi#subdirs as the format. * @param fileURIStr uri with fragment * @return array of file name, subdirs, checksum and source CM root URI */ public static String[] decodeFileUri(String fileURIStr) { String[] uriAndFragment = fileURIStr.split(URI_FRAGMENT_SEPARATOR); String[] result = new String[4]; result[0] = uriAndFragment[0]; if ((uriAndFragment.length > 1) && !StringUtils.isEmpty(uriAndFragment[1])) { result[1] = uriAndFragment[1]; } if ((uriAndFragment.length > 2) && !StringUtils.isEmpty(uriAndFragment[2])) { result[2] = uriAndFragment[2]; } if ((uriAndFragment.length > 3) && !StringUtils.isEmpty(uriAndFragment[3])) { result[3] = uriAndFragment[3]; } if (LOG.isDebugEnabled()) { LOG.debug("Reading Encoded URI: " + result[0] + ":: " + result[1] + ":: " + result[2] + ":: " + result[3]); } return result; } public static boolean isCMFileUri(Path fromPath) { String[] result = decodeFileUri(fromPath.toString()); return result[1] != null; } /** * Thread to clear old files of cmroot recursively */ static class CMClearer implements Runnable { private Path cmroot; private long secRetain; private Configuration conf; CMClearer(String cmrootString, long secRetain, Configuration conf) { this.cmroot = new Path(cmrootString); this.secRetain = secRetain; this.conf = conf; } @Override public void run() { try { LOG.info("CMClearer started"); long now = System.currentTimeMillis(); FileSystem fs = cmroot.getFileSystem(conf); FileStatus[] files = fs.listStatus(cmroot); for (FileStatus file : files) { long modifiedTime = file.getModificationTime(); if (now - modifiedTime > secRetain*1000) { try { if (fs.getXAttrs(file.getPath()).containsKey(REMAIN_IN_TRASH_TAG)) { boolean succ = Trash.moveToAppropriateTrash(fs, file.getPath(), conf); if (succ) { if (LOG.isDebugEnabled()) { LOG.debug("Move " + file.toString() + " to trash"); } } else { LOG.warn("Fail to move " + file.toString() + " to trash"); } } else { boolean succ = fs.delete(file.getPath(), false); if (succ) { if (LOG.isDebugEnabled()) { LOG.debug("Remove " + file.toString()); } } else { LOG.warn("Fail to remove " + file.toString()); } } } catch (UnsupportedOperationException e) { LOG.warn("Error getting xattr for " + file.getPath().toString()); } } } } catch (IOException e) { LOG.error("Exception when clearing cmroot:" + StringUtils.stringifyException(e)); } } } // Schedule CMClearer thread. Will be invoked by metastore static void scheduleCMClearer(Configuration conf) { if (MetastoreConf.getBoolVar(conf, ConfVars.REPLCMENABLED)) { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor( new BasicThreadFactory.Builder() .namingPattern("cmclearer-%d") .daemon(true) .build()); executor.scheduleAtFixedRate(new CMClearer(MetastoreConf.getVar(conf, ConfVars.REPLCMDIR), MetastoreConf.getTimeVar(conf, ConfVars.REPLCMRETIAN, TimeUnit.SECONDS), conf), 0, MetastoreConf.getTimeVar(conf, ConfVars.REPLCMINTERVAL, TimeUnit.SECONDS), TimeUnit.SECONDS); } } public static boolean isSourceOfReplication(Database db) { // Can not judge, so assuming replication is not enabled. assert (db != null); String replPolicyIds = getReplPolicyIdString(db); return !StringUtils.isEmpty(replPolicyIds); } public static String getReplPolicyIdString(Database db) { if (db != null) { Map<String, String> m = db.getParameters(); if ((m != null) && (m.containsKey(SOURCE_OF_REPLICATION))) { String replPolicyId = m.get(SOURCE_OF_REPLICATION); LOG.debug("repl policy for database {} is {}", db.getName(), replPolicyId); return replPolicyId; } LOG.debug("Repl policy is not set for database ", db.getName()); } return null; } }
/* * Copyright (c) 2016 Intland Software (support@intland.com) */ package com.intland.jenkins.api.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonIgnoreProperties(ignoreUnknown = true) @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public class TrackerTypeSettingDto { private Integer id; private String name; public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } }
package com.erzhiqianyi.leecode.string; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; public class StrStrTest { private StrStr strStr; @Before public void init() { strStr = new StrStr(); } @Test public void strStr() { String haystack = "hello"; String needle="ll"; int expect = 2; int result = strStr.strStr(haystack,needle); assertEquals(expect,result); } }
/*- * << * DBus * == * Copyright (C) 2016 - 2017 Bridata * == * 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.creditease.dbus.stream.common.tools; import com.creditease.dbus.commons.DBusConsumerRecord; import com.creditease.dbus.stream.common.DataSourceInfo; import com.creditease.dbus.commons.Constants; import com.creditease.dbus.commons.StatMessage; import com.creditease.dbus.stream.common.bean.DispatcherPackage; import org.apache.kafka.clients.producer.Callback; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.javatuples.Quartet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.Future; /** * Created by dongwang47 on 2016/8/18. */ public abstract class MessageProcessor { protected Logger logger = LoggerFactory.getLogger(getClass()); protected String statTopic; protected DataSourceInfo dsInfo; protected KafkaProducer<String, String> producer = null; public List<IGenericMessage> messageList = null; //stat info about count map, key is ds.schema.table, value is COUNT. protected TableStatMap statMap = null; protected Properties schemaTopicProps = null; //public List<OracleGenericMessage> messageList = null; public MessageProcessor(DataSourceInfo dsInfo, String statTopic, Properties producerProps, TableStatMap statMap, Properties schemaTopicProps) throws Exception { this.dsInfo = dsInfo; this.statTopic = statTopic; this.producer = new KafkaProducer<>(producerProps); logger.info("stat producer is ready."); this.statMap = statMap; this.schemaTopicProps = schemaTopicProps; } public void cleanup() throws Exception { if (producer != null) { producer.close(); producer = null; } } public String getSchemaTopic(String schemaName) { if (schemaTopicProps != null) { String topicName = schemaTopicProps.getProperty(schemaName); if (topicName != null) { return topicName; } } //没有定义schema对应的topic,使用规则名称,schema就是topic名称 return dsInfo.getDbSourceName() + "." + schemaName; } /** * template method getNextList * @return * @throws IOException */ public List<DispatcherPackage> getNextList() throws IOException { String ctrlMessageKey = null; assert (messageList != null); Iterator<IGenericMessage> iter = messageList.iterator(); if (!iter.hasNext()) { messageList = null; return null; } // 1.根据schema 创建不同的hash map Map<String, List<IGenericMessage>> map = new HashMap<>(); IGenericMessage msg; while(iter.hasNext()) { msg = iter.next(); String schemaName = msg.getSchemaName(); String tableName = msg.getTableName(); int rowCount = msg.getRowCount(); logger.debug(String.format("schemaName = %s, tableName = %s", schemaName, tableName)); if (schemaName.equalsIgnoreCase(dsInfo.getDbusSchema())) { if (tableName.equalsIgnoreCase(Constants.FULL_PULL_TABLE)) { if (map.size() != 0) { logger.debug("这是中间的某一条是dbus数据,前面包含其他schema的数据,需要将前面的包先发送掉"); break; } if (processFullPullerMessage(map, msg) == 0) { //正常情况 ctrlMessageKey = msg.getNameSpace() + "." + msg.getSchemaHash(); iter.remove(); break; } else { iter.remove(); //非insert的数据, 跳过了一条不需要传递的message continue; } } else if (tableName.equalsIgnoreCase(Constants.META_SYNC_EVENT_TABLE)) { if (map.size() != 0) { logger.debug("这是中间的某一条是dbus数据,前面包含其他schema的数据"); break; } if (processMetaSyncMessage(map, msg) == 0) { //正常情况 ctrlMessageKey = msg.getNameSpace() + "." + msg.getSchemaHash(); iter.remove(); break; } else { iter.remove(); //非insert的数据 ,跳过了一条不需要传递的message continue; } } else if (tableName.equalsIgnoreCase(Constants.HEARTBEAT_MONITOR_TABLE)) { //根据SCHEMA_NAME发送对于的topic数据,不单独发 processHeartBeatMessage(map, msg); iter.remove(); continue; } } //只有数据进行统计 if (msg.isDML()) { statMark(schemaName, tableName, rowCount); } //按照schema来分包,因为schema对应不同topic List<IGenericMessage> subList = map.get(schemaName); if (subList != null) { subList.add(msg); } else { subList = new LinkedList<>(); subList.add(msg); map.put(schemaName, subList); } iter.remove(); //remove this message } // 2 将每个sublist 打包成为 byte[] List<DispatcherPackage> tuples = new LinkedList<>(); for (HashMap.Entry<String, List<IGenericMessage>> entry : map.entrySet()) { List<IGenericMessage> subList = entry.getValue(); byte[] content = wrapMessages(subList); String schemaName = entry.getKey(); int msgCount = subList.size(); String toTopic = getSchemaTopic(schemaName); tuples.add(new DispatcherPackage(ctrlMessageKey, content, msgCount, schemaName, toTopic)); } return tuples; } /** * template method, unwapMessage * @param record * @throws IOException */ public void preProcess(DBusConsumerRecord<String, byte[]> record) throws IOException { messageList = unwrapMessages((byte[]) record.value()); logger.info(String.format("Got Data : offset=%d, total_msg_count=%d, serializedValueSize=%d, from_topic: %s", record.offset(), messageList.size(), record.serializedValueSize(), record.topic())); } /*** * send stat info to statistic topic, do not care about success or not. * @param message */ private void sendTableStatInfo(StatMessage message) { String key = String.format("%s.%s.%s.%s.%s", message.getDsName(), message.getSchemaName(), message.getTableName(), message.getType(), message.getTxTimeMS()); String value = message.toJSONString(); Callback callback = new Callback() { @Override public void onCompletion(RecordMetadata ignored, Exception e) { if (e != null) { logger.error(String.format("Send statistic FAIL: toTopic=%s, key=%s", statTopic, key)); } else { logger.info(String.format(" Send statistic successful: toTopic=%s, key=(%s)", statTopic, key)); } } }; Future<RecordMetadata> result = producer.send(new ProducerRecord<>(statTopic, key, value), callback); } //统计信息并插入到stat的kafka中 public void statMeter(String schemaName, String tableName, long checkpointMS, long txTimeMS) { StatMessage message = statMap.logMeter(schemaName, tableName, checkpointMS, txTimeMS); sendTableStatInfo (message); message.cleanUp(); } //统计技术 public void statMark(String schemaName, String tableName, long count) { statMap.mark(schemaName, tableName, count); } public abstract List<IGenericMessage> unwrapMessages(byte[] data) throws IOException; public abstract byte[] wrapMessages(List<IGenericMessage> list) throws IOException; public abstract int processMetaSyncMessage(Map<String, List<IGenericMessage>> map, IGenericMessage obj) throws IOException; public abstract int processFullPullerMessage(Map<String, List<IGenericMessage>> map, IGenericMessage obj) throws IOException; public abstract int processHeartBeatMessage(Map<String, List<IGenericMessage>> map, IGenericMessage obj) throws IOException; }
/* * Copyright (c) 2003, 2013, 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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 sun.net.spi; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.ProxySelector; import java.net.SocketAddress; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.io.IOException; import sun.misc.RegexpPool; import java.security.AccessController; import java.security.PrivilegedAction; import sun.net.NetProperties; import sun.net.SocksProxy; /** * Supports proxy settings using system properties This proxy selector * provides backward compatibility with the old http protocol handler * as far as how proxy is set * * Most of the implementation copied from the old http protocol handler * * Supports http/https/ftp.proxyHost, http/https/ftp.proxyPort, * proxyHost, proxyPort, and http/https/ftp.nonProxyHost, and socks. * NOTE: need to do gopher as well */ public class DefaultProxySelector extends ProxySelector { /** * This is where we define all the valid System Properties we have to * support for each given protocol. * The format of this 2 dimensional array is : * - 1 row per protocol (http, ftp, ...) * - 1st element of each row is the protocol name * - subsequent elements are prefixes for Host & Port properties * listed in order of priority. * Example: * {"ftp", "ftp.proxy", "ftpProxy", "proxy", "socksProxy"}, * means for FTP we try in that oder: * + ftp.proxyHost & ftp.proxyPort * + ftpProxyHost & ftpProxyPort * + proxyHost & proxyPort * + socksProxyHost & socksProxyPort * * Note that the socksProxy should *always* be the last on the list */ final static String[][] props = { /* * protocol, Property prefix 1, Property prefix 2, ... */ {"http", "http.proxy", "proxy", "socksProxy"}, {"https", "https.proxy", "proxy", "socksProxy"}, {"ftp", "ftp.proxy", "ftpProxy", "proxy", "socksProxy"}, {"gopher", "gopherProxy", "socksProxy"}, {"socket", "socksProxy"} }; private static final String SOCKS_PROXY_VERSION = "socksProxyVersion"; private static boolean hasSystemProxies = false; static { final String key = "java.net.useSystemProxies"; Boolean b = AccessController.doPrivileged( new PrivilegedAction<Boolean>() { public Boolean run() { return NetProperties.getBoolean(key); }}); if (b != null && b.booleanValue()) { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<Void>() { public Void run() { System.loadLibrary("net"); return null; } }); hasSystemProxies = init(); } } /** * How to deal with "non proxy hosts": * since we do have to generate a RegexpPool we don't want to do that if * it's not necessary. Therefore we do cache the result, on a per-protocol * basis, and change it only when the "source", i.e. the system property, * did change. */ static class NonProxyInfo { // Default value for nonProxyHosts, this provides backward compatibility // by excluding localhost and its litteral notations. static final String defStringVal = "localhost|127.*|[::1]|0.0.0.0|[::0]"; String hostsSource; RegexpPool hostsPool; final String property; final String defaultVal; static NonProxyInfo ftpNonProxyInfo = new NonProxyInfo("ftp.nonProxyHosts", null, null, defStringVal); static NonProxyInfo httpNonProxyInfo = new NonProxyInfo("http.nonProxyHosts", null, null, defStringVal); static NonProxyInfo socksNonProxyInfo = new NonProxyInfo("socksNonProxyHosts", null, null, defStringVal); NonProxyInfo(String p, String s, RegexpPool pool, String d) { property = p; hostsSource = s; hostsPool = pool; defaultVal = d; } } /** * select() method. Where all the hard work is done. * Build a list of proxies depending on URI. * Since we're only providing compatibility with the system properties * from previous releases (see list above), that list will always * contain 1 single proxy, default being NO_PROXY. */ public java.util.List<Proxy> select(URI uri) { if (uri == null) { throw new IllegalArgumentException("URI can't be null."); } String protocol = uri.getScheme(); String host = uri.getHost(); if (host == null) { // This is a hack to ensure backward compatibility in two // cases: 1. hostnames contain non-ascii characters, // internationalized domain names. in which case, URI will // return null, see BugID 4957669; 2. Some hostnames can // contain '_' chars even though it's not supposed to be // legal, in which case URI will return null for getHost, // but not for getAuthority() See BugID 4913253 String auth = uri.getAuthority(); if (auth != null) { int i; i = auth.indexOf('@'); if (i >= 0) { auth = auth.substring(i+1); } i = auth.lastIndexOf(':'); if (i >= 0) { auth = auth.substring(0,i); } host = auth; } } if (protocol == null || host == null) { throw new IllegalArgumentException("protocol = "+protocol+" host = "+host); } List<Proxy> proxyl = new ArrayList<Proxy>(1); NonProxyInfo pinfo = null; if ("http".equalsIgnoreCase(protocol)) { pinfo = NonProxyInfo.httpNonProxyInfo; } else if ("https".equalsIgnoreCase(protocol)) { // HTTPS uses the same property as HTTP, for backward // compatibility pinfo = NonProxyInfo.httpNonProxyInfo; } else if ("ftp".equalsIgnoreCase(protocol)) { pinfo = NonProxyInfo.ftpNonProxyInfo; } else if ("socket".equalsIgnoreCase(protocol)) { pinfo = NonProxyInfo.socksNonProxyInfo; } /** * Let's check the System properties for that protocol */ final String proto = protocol; final NonProxyInfo nprop = pinfo; final String urlhost = host.toLowerCase(); /** * This is one big doPrivileged call, but we're trying to optimize * the code as much as possible. Since we're checking quite a few * System properties it does help having only 1 call to doPrivileged. * Be mindful what you do in here though! */ Proxy p = AccessController.doPrivileged( new PrivilegedAction<Proxy>() { public Proxy run() { int i, j; String phost = null; int pport = 0; String nphosts = null; InetSocketAddress saddr = null; // Then let's walk the list of protocols in our array for (i=0; i<props.length; i++) { if (props[i][0].equalsIgnoreCase(proto)) { for (j = 1; j < props[i].length; j++) { /* System.getProp() will give us an empty * String, "" for a defined but "empty" * property. */ phost = NetProperties.get(props[i][j]+"Host"); if (phost != null && phost.length() != 0) break; } if (phost == null || phost.length() == 0) { /** * No system property defined for that * protocol. Let's check System Proxy * settings (Gnome & Windows) if we were * instructed to. */ if (hasSystemProxies) { String sproto; if (proto.equalsIgnoreCase("socket")) sproto = "socks"; else sproto = proto; Proxy sproxy = getSystemProxy(sproto, urlhost); if (sproxy != null) { return sproxy; } } return Proxy.NO_PROXY; } // If a Proxy Host is defined for that protocol // Let's get the NonProxyHosts property if (nprop != null) { nphosts = NetProperties.get(nprop.property); synchronized (nprop) { if (nphosts == null) { if (nprop.defaultVal != null) { nphosts = nprop.defaultVal; } else { nprop.hostsSource = null; nprop.hostsPool = null; } } else if (nphosts.length() != 0) { // add the required default patterns // but only if property no set. If it // is empty, leave empty. nphosts += "|" + NonProxyInfo .defStringVal; } if (nphosts != null) { if (!nphosts.equals(nprop.hostsSource)) { RegexpPool pool = new RegexpPool(); StringTokenizer st = new StringTokenizer(nphosts, "|", false); try { while (st.hasMoreTokens()) { pool.add(st.nextToken().toLowerCase(), Boolean.TRUE); } } catch (sun.misc.REException ex) { } nprop.hostsPool = pool; nprop.hostsSource = nphosts; } } if (nprop.hostsPool != null && nprop.hostsPool.match(urlhost) != null) { return Proxy.NO_PROXY; } } } // We got a host, let's check for port pport = NetProperties.getInteger(props[i][j]+"Port", 0).intValue(); if (pport == 0 && j < (props[i].length - 1)) { // Can't find a port with same prefix as Host // AND it's not a SOCKS proxy // Let's try the other prefixes for that proto for (int k = 1; k < (props[i].length - 1); k++) { if ((k != j) && (pport == 0)) pport = NetProperties.getInteger(props[i][k]+"Port", 0).intValue(); } } // Still couldn't find a port, let's use default if (pport == 0) { if (j == (props[i].length - 1)) // SOCKS pport = defaultPort("socket"); else pport = defaultPort(proto); } // We did find a proxy definition. // Let's create the address, but don't resolve it // as this will be done at connection time saddr = InetSocketAddress.createUnresolved(phost, pport); // Socks is *always* the last on the list. if (j == (props[i].length - 1)) { int version = NetProperties.getInteger(SOCKS_PROXY_VERSION, 5).intValue(); return SocksProxy.create(saddr, version); } else { return new Proxy(Proxy.Type.HTTP, saddr); } } } return Proxy.NO_PROXY; }}); proxyl.add(p); /* * If no specific property was set for that URI, we should be * returning an iterator to an empty List. */ return proxyl; } public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { if (uri == null || sa == null || ioe == null) { throw new IllegalArgumentException("Arguments can't be null."); } // ignored } private int defaultPort(String protocol) { if ("http".equalsIgnoreCase(protocol)) { return 80; } else if ("https".equalsIgnoreCase(protocol)) { return 443; } else if ("ftp".equalsIgnoreCase(protocol)) { return 80; } else if ("socket".equalsIgnoreCase(protocol)) { return 1080; } else if ("gopher".equalsIgnoreCase(protocol)) { return 80; } else { return -1; } } private native static boolean init(); private synchronized native Proxy getSystemProxy(String protocol, String host); }
/* * 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.wipro.ats.bdre.md.dao; import com.wipro.ats.bdre.exception.MetadataException; import com.wipro.ats.bdre.md.dao.jpa.ArchiveConsumpQueue; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Created by MR299389 on 10/15/2015. */ @Transactional @Service public class ArchiveConsumpQueueDAO { private static final Logger LOGGER = Logger.getLogger(ArchiveConsumpQueueDAO.class); @Autowired SessionFactory sessionFactory; public List<ArchiveConsumpQueue> list(Integer pageNum, Integer numResults) { Session session = sessionFactory.openSession(); session.beginTransaction(); Criteria criteria = session.createCriteria(ArchiveConsumpQueue.class); criteria.setFirstResult(pageNum); criteria.setMaxResults(numResults); List<ArchiveConsumpQueue> archiveConsumpQueues = criteria.list(); session.getTransaction().commit(); session.close(); return archiveConsumpQueues; } public Long totalRecordCount() { Session session = sessionFactory.openSession(); session.beginTransaction(); Criteria criteria = session.createCriteria(ArchiveConsumpQueue.class); long size = criteria.list().size(); session.getTransaction().commit(); session.close(); return size; } public ArchiveConsumpQueue get(Long id) { Session session = sessionFactory.openSession(); session.beginTransaction(); ArchiveConsumpQueue archiveConsumpQueue = (ArchiveConsumpQueue) session.get(ArchiveConsumpQueue.class, id); session.getTransaction().commit(); session.close(); return archiveConsumpQueue; } public Long insert(ArchiveConsumpQueue archiveConsumpQueue) { Session session = sessionFactory.openSession(); Long id = null; try { session.beginTransaction(); id = (Long) session.save(archiveConsumpQueue); session.getTransaction().commit(); } catch (MetadataException e) { session.getTransaction().rollback(); LOGGER.error(e); } finally { session.close(); } return id; } public void update(ArchiveConsumpQueue archiveConsumpQueue) { Session session = sessionFactory.openSession(); try { session.beginTransaction(); session.update(archiveConsumpQueue); session.getTransaction().commit(); } catch (MetadataException e) { session.getTransaction().rollback(); LOGGER.error(e); } finally { session.close(); } } public void delete(Long id) { Session session = sessionFactory.openSession(); try { session.beginTransaction(); ArchiveConsumpQueue archiveConsumpQueue = (ArchiveConsumpQueue) session.get(ArchiveConsumpQueue.class, id); session.delete(archiveConsumpQueue); session.getTransaction().commit(); } catch (MetadataException e) { session.getTransaction().rollback(); LOGGER.error(e); } finally { session.close(); } } }
/* * Copyright 2014 Bersenev Dmitry molasdin@outlook.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.molasdin.wbase.hibernate.search; import org.hibernate.criterion.MatchMode; import org.molasdin.wbase.storage.Order; /** * Created by dbersenev on 24.02.14. */ public interface QueryBuilder { QueryBuilder addPart(String value); QueryBuilder addFrom(String name, String alias); QueryBuilder addInnerJoin(String prop, String alias); QueryBuilder addWhere(BuilderScope scope, boolean isEnabled); QueryBuilder ilikeWild(String prop, String value, MatchMode mode); QueryBuilder gt(String prop, String param); QueryBuilder lt(String prop, String param); QueryBuilder addOrder(String prop, Order order); String query(); }
package com.baomidou.mybatisplus.extension.plugins.pagination; import com.baomidou.mybatisplus.core.metadata.OrderItem; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.statement.select.PlainSelect; import net.sf.jsqlparser.statement.select.Select; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * SelectBody强转PlainSelect不支持sql里面最外层带union * 用SetOperationList处理sql带union的语句 */ class SelectBodyToPlainSelectTest { /** * 报错的测试 */ @Test void testSelectBodyToPlainSelectThrowException() { Select selectStatement = null; try { String originalUnionSql = "select * from test union select * from test"; selectStatement = (Select) CCJSqlParserUtil.parse(originalUnionSql); } catch (JSQLParserException e) { e.printStackTrace(); } assert selectStatement != null; Select finalSelectStatement = selectStatement; Assertions.assertThrows(ClassCastException.class, () -> { PlainSelect plainSelect = (PlainSelect) finalSelectStatement.getSelectBody(); }); } private Page<?> page = new Page<>(); @BeforeEach void setup() { List<OrderItem> orderItems = new ArrayList<>(); OrderItem order = new OrderItem(); order.setAsc(true); order.setColumn("column"); orderItems.add(order); OrderItem orderEmptyColumn = new OrderItem(); orderEmptyColumn.setAsc(false); orderEmptyColumn.setColumn(""); orderItems.add(orderEmptyColumn); page.setOrders(orderItems); } @Test void testPaginationInterceptorConcatOrderByBefore() { String actualSql = PaginationInterceptor .concatOrderBy("select * from test", page); assertThat(actualSql).isEqualTo("SELECT * FROM test ORDER BY column ASC"); String actualSqlWhere = PaginationInterceptor .concatOrderBy("select * from test where 1 = 1", page); assertThat(actualSqlWhere).isEqualTo("SELECT * FROM test WHERE 1 = 1 ORDER BY column ASC"); } @Test void testPaginationInterceptorConcatOrderByFix() { String actualSql = PaginationInterceptor .concatOrderBy("select * from test union select * from test2", page); assertThat(actualSql).isEqualTo("SELECT * FROM test UNION SELECT * FROM test2 ORDER BY column ASC"); String actualSqlUnionAll = PaginationInterceptor .concatOrderBy("select * from test union all select * from test2", page); assertThat(actualSqlUnionAll).isEqualTo("SELECT * FROM test UNION ALL SELECT * FROM test2 ORDER BY column ASC"); } @Test void testPaginationInterceptorConcatOrderByFixWithWhere() { String actualSqlWhere = PaginationInterceptor .concatOrderBy("select * from test where 1 = 1 union select * from test2 where 1 = 1", page); assertThat(actualSqlWhere).isEqualTo("SELECT * FROM test WHERE 1 = 1 UNION SELECT * FROM test2 WHERE 1 = 1 ORDER BY column ASC"); String actualSqlUnionAll = PaginationInterceptor .concatOrderBy("select * from test where 1 = 1 union all select * from test2 where 1 = 1 ", page); assertThat(actualSqlUnionAll).isEqualTo("SELECT * FROM test WHERE 1 = 1 UNION ALL SELECT * FROM test2 WHERE 1 = 1 ORDER BY column ASC"); } @Test void testPaginationInterceptorOrderByEmptyColumnFix() { String actualSql = PaginationInterceptor .concatOrderBy("select * from test", page); assertThat(actualSql).isEqualTo("SELECT * FROM test ORDER BY column ASC"); String actualSqlWhere = PaginationInterceptor .concatOrderBy("select * from test where 1 = 1", page); assertThat(actualSqlWhere).isEqualTo("SELECT * FROM test WHERE 1 = 1 ORDER BY column ASC"); } }
/* * Copyright 2020 Jakob Hjelm (Komposten) * * This file is part of LeapJna. * * LeapJna is a free Java library: you can use, redistribute it and/or modify * it under the terms of the MIT license as written in the LICENSE file in the root * of this project. */ package komposten.leapjna.leapc.events; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.Structure.FieldOrder; import com.sun.jna.ptr.LongByReference; import komposten.leapjna.leapc.LeapC; import komposten.leapjna.leapc.data.LEAP_CONNECTION_MESSAGE; import komposten.leapjna.leapc.data.LEAP_VARIANT; /** * <p> * Contains the response to a configuration value request. * </p> * <p> * Call {@link LeapC#LeapRequestConfigValue(Pointer, String, LongByReference)} to request a * service config value. The value is fetched asynchronously since it requires a service * transaction. {@link LeapC#LeapPollConnection(Pointer, int, LEAP_CONNECTION_MESSAGE)} * returns this event structure when the request has been processed. Use the requestID * value to correlate the response to the originating request. * </p> * * @see <a href= * "https://developer.leapmotion.com/documentation/v4/group___structs.html#struct_l_e_a_p___c_o_n_f_i_g___r_e_s_p_o_n_s_e___e_v_e_n_t">LeapC * API - LEAP_CONFIG_RESPONSE_EVENT</a> */ @FieldOrder({ "requestID", "value" }) public class LEAP_CONFIG_RESPONSE_EVENT extends Structure implements LEAP_EVENT { /** An identifier for correlating the request and response. */ public int requestID; /** * The configuration value retrieved from the service. Do not free any memory pointed to * by this member. The value held is only valid until the next call to * {@link LeapC#LeapPollConnection(Pointer, int, LEAP_CONNECTION_MESSAGE)}. */ public LEAP_VARIANT value; public LEAP_CONFIG_RESPONSE_EVENT(Pointer pointer) { super(pointer, ALIGN_NONE); read(); } }
package de.sprax2013.lime.configuration; import de.sprax2013.lime.configuration.validation.EntryValidator; import de.sprax2013.lime.legacy.LegacyKeyUpgrader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * A {@link ConfigEntry} consist of an {@code key}, a given {@code defaultValue} and the current {@code value} * read from the file or set by the developer.<br><br> * You can additionally assign an {@link EntryValidator} and {@link ConfigCommentProvider}. * * @see Config#createEntry(String, Object) * @see Config#withEntry(String, Object) * @see Config#addCommentEntry(String, String) * @see Config#withCommentEntry(String, String) */ @SuppressWarnings({"UnusedReturnValue", "unused"}) public class ConfigEntry { private final @NotNull String key; private final @Nullable Object defaultValue; private @Nullable EntryValidator entryValidator; private @Nullable ConfigCommentProvider commentProvider; private @Nullable Map<Integer, LegacyConfigKey> legacyKeys; private Object value; /** * @param key An unique identifier within the {@link Config} * @param defaultValue The default value for this entry * * @see EntryValidator */ protected ConfigEntry(@NotNull String key, @Nullable Object defaultValue) { this(key, defaultValue, null); } /** * @param key An unique identifier within the {@link Config} * @param defaultValue The default value for this entry * @param commentProvider A {@link ConfigCommentProvider} that generates a comment or null * * @see EntryValidator * @see ConfigCommentProvider */ protected ConfigEntry(@NotNull String key, @Nullable Object defaultValue, @Nullable ConfigCommentProvider commentProvider) { this.key = Objects.requireNonNull(key); this.defaultValue = defaultValue; this.commentProvider = commentProvider; this.value = defaultValue; } /** * The key is unique within a {@link Config}, thus there can be same keys in differen {@link Config}s.<br><br> * Every {@code .} inside the {@code key} causes one indentation further down the tree.<br><br> * <p> * e.g. {@code "Root.Profile.Username"} turns into the following YAML structure:<br> * {@code Root:}<br> * &nbsp;&nbsp;{@code Profile:}<br> * &nbsp;&nbsp;&nbsp;&nbsp;{@code Username: [Value]} * * @return The unique identifier that has been assigned to this {@link ConfigEntry} */ public @NotNull String getKey() { return this.key; } /** * @return The default value that has been provided via the constructor * * @see #ConfigEntry(String, Object) * @see #ConfigEntry(String, Object, ConfigCommentProvider) */ public @Nullable Object getDefaultValue() { return this.defaultValue; } /** * @param entryValidator The {@link EntryValidator} to use, or {@code null} * * @return The same {@link ConfigEntry} for chaining * * @see EntryValidator * @see #getEntryValidator() */ public @NotNull ConfigEntry setEntryValidator(@Nullable EntryValidator entryValidator) { if (entryValidator != null && !entryValidator.isValid(this.defaultValue)) throw new IllegalArgumentException("The EntryValidator returns false for the Entry's default value"); this.entryValidator = entryValidator; return this; } /** * @return The {@link EntryValidator} assigned, or {@code null} * * @see EntryValidator * @see #setEntryValidator(EntryValidator) */ public @Nullable EntryValidator getEntryValidator() { return this.entryValidator; } /** * <em>Be informed, that according to the YAML 1.1 spec, * comments may not associated with a particular node (witch is exactly what this method is for)</em> * * @param commentProvider The {@link ConfigCommentProvider} to use, or {@code null} * * @return The same {@link ConfigEntry} for chaining * * @see <a href="https://yaml.org/spec/1.1/current.html#id864687">YAML 1.1 spec</a> * @see ConfigCommentProvider * @see #getCommentProvider() */ public @NotNull ConfigEntry setCommentProvider(@Nullable ConfigCommentProvider commentProvider) { this.commentProvider = commentProvider; return this; } /** * @return The {@link ConfigCommentProvider} assigned, or {@code null} * * @see ConfigCommentProvider * @see #setCommentProvider(ConfigCommentProvider) */ public @Nullable ConfigCommentProvider getCommentProvider() { return this.commentProvider; } /** * This method adds the {@code #} to the beginning of the lines, to tell the YAML parser to ignore these lines<br> * This method might apply more complex structures according to the defined {@link CommentStyle}. * * @return Formatted comment {@link String}, or {@code null} * * @see CommentStyle * @see #setCommentProvider(ConfigCommentProvider) * @see #getCommentProvider() */ public @Nullable String getFormattedComment() { String comment = this.commentProvider != null ? this.commentProvider.getComment() : null; if (comment != null && !comment.isEmpty()) { return "# " + comment.replaceAll("\n", "\n# "); } return null; } public @NotNull ConfigEntry setLegacyKey(int cfgVersion, @Nullable String legacyKey) { return setLegacyKey(cfgVersion, legacyKey, null); } public @NotNull ConfigEntry setLegacyKey(int cfgVersion, @Nullable String legacyKey, @Nullable LegacyKeyUpgrader keyUpgrader) { if (this.legacyKeys == null) { this.legacyKeys = new HashMap<>(1, 1); } this.legacyKeys.put(cfgVersion, new LegacyConfigKey(legacyKey, keyUpgrader)); return this; } public @Nullable LegacyConfigKey getLegacyKey(int cfgVersionAtThatTime) { return this.legacyKeys != null ? this.legacyKeys.get(cfgVersionAtThatTime) : null; } /** * Sets the {@code value}.<br> * <strong>Arrays are automatically converted into a {@link List}!</strong> * * @param value The value to set the entry to * * @return The same {@link ConfigEntry} for chaining * * @see #getValue() * @see #getDefaultValue() */ public @NotNull ConfigEntry setValue(@Nullable Object value) { this.value = value instanceof Object[] ? Arrays.asList((Object[]) value) : value; return this; } /** * @return Returns the current value as is (can be {@code null}) * * @see #getDefaultValue() * @see #setValue(Object) * @see #getValue(Object) * @see #getValueAsBoolean() * @see #getValueAsDouble() * @see #getValueAsFloat() * @see #getValueAsInt() * @see #getValueAsLong() * @see #getValueAsString() * @see #getValueAsList() * @see #getValueAsStringList() */ public @Nullable Object getValue() { return this.value; } /** * @param type The type, the value should be casted to * @param <T> The type, the value should be casted to * * @return Returns the current value casted to the given type (can be {@code null}) * * @see #getDefaultValue() * @see #setValue(Object) * @see #getValue() * @see #getValueAsBoolean() * @see #getValueAsDouble() * @see #getValueAsFloat() * @see #getValueAsInt() * @see #getValueAsLong() * @see #getValueAsString() * @see #getValueAsList() * @see #getValueAsStringList() */ @SuppressWarnings("unchecked") public @Nullable <T> T getValue(T type) { return (T) this.value; } /** * @return True if {@link #getValue()} {@code != null}, false otherwise */ public boolean hasValue() { return this.value != null; } public <T extends Enum<T>> T getValueAsEnum(Class<T> enumType) { Object result; if (entryValidator == null || entryValidator.isValid(this.value)) { result = this.value; } else { result = this.defaultValue; } if (result instanceof String) { return Enum.valueOf(enumType, (String) result); } if (enumType.isInstance(result)) { return enumType.cast(result); } return null; } /** * If {@link EntryValidator} is not {@code null} and {@link EntryValidator#isValid(Object)} is {@code false}, * the {@code defaultValue} will be used instead.<br> * <p> * One of these two values is then casted to a {@code boolean} (if it is an {@code boolean}) * or it is casted to a {@link String} and fed into {@link Boolean#parseBoolean(String)} * * @return Returns one of the values as a {@code boolean} * * @see Boolean#parseBoolean(String) * @see #getDefaultValue() * @see #setValue(Object) * @see #getValue() * @see #getValue(Object) * @see #getValueAsDouble() * @see #getValueAsFloat() * @see #getValueAsInt() * @see #getValueAsLong() * @see #getValueAsString() * @see #getValueAsList() * @see #getValueAsStringList() */ public boolean getValueAsBoolean() { Object result; if (entryValidator == null || entryValidator.isValid(this.value)) { result = this.value; } else { result = this.defaultValue; } return result instanceof Boolean ? (boolean) result : Boolean.parseBoolean((String) result); } /** * If {@link EntryValidator} is not {@code null} and {@link EntryValidator#isValid(Object)} is {@code false}, * the {@code defaultValue} will be used instead.<br> * <p> * One of these two values is then casted to a {@code int} (if it is an {@code int}) * or it is casted to a {@link String} and fed into {@link Integer#parseInt(String)} * * @return Returns one of the value as an {@code int} * * @see Integer#parseInt(String) * @see #getDefaultValue() * @see #setValue(Object) * @see #getValue() * @see #getValue(Object) * @see #getValueAsBoolean() * @see #getValueAsDouble() * @see #getValueAsFloat() * @see #getValueAsLong() * @see #getValueAsString() * @see #getValueAsList() * @see #getValueAsStringList() */ public int getValueAsInt() { Object result; if (entryValidator == null || entryValidator.isValid(this.value)) { result = this.value; } else { result = this.defaultValue; } if (result == null) return 0; return result instanceof Number ? ((Number) result).intValue() : Integer.parseInt((String) result); } /** * If {@link EntryValidator} is not {@code null} and {@link EntryValidator#isValid(Object)} is {@code false}, * the {@code defaultValue} will be used instead.<br> * <p> * One of these two values is then casted to a {@code long} (if it is an {@code long}) * or it is casted to a {@link String} and fed into {@link Long#parseLong(String)} * * @return Returns one of the value as an {@code long} * * @see Long#parseLong(String) * @see #getDefaultValue() * @see #setValue(Object) * @see #getValue() * @see #getValue(Object) * @see #getValueAsBoolean() * @see #getValueAsDouble() * @see #getValueAsFloat() * @see #getValueAsInt() * @see #getValueAsString() * @see #getValueAsList() * @see #getValueAsStringList() */ public long getValueAsLong() { Object result; if (entryValidator == null || entryValidator.isValid(this.value)) { result = this.value; } else { result = this.defaultValue; } if (result == null) return 0; return result instanceof Number ? ((Number) result).longValue() : Long.parseLong((String) result); } /** * If {@link EntryValidator} is not {@code null} and {@link EntryValidator#isValid(Object)} is {@code false}, * the {@code defaultValue} will be used instead.<br> * One of these two values is then casted to a {@code float} (if it is an {@code float}) * or it is casted to a {@link String} and fed into {@link Float#parseFloat(String)} * * @return Returns one of the value as an {@code float} * * @see Float#parseFloat(String) * @see #getDefaultValue() * @see #setValue(Object) * @see #getValue() * @see #getValue(Object) * @see #getValueAsBoolean() * @see #getValueAsDouble() * @see #getValueAsInt() * @see #getValueAsLong() * @see #getValueAsString() * @see #getValueAsList() * @see #getValueAsStringList() */ public float getValueAsFloat() { Object result; if (entryValidator == null || entryValidator.isValid(this.value)) { result = this.value; } else { result = this.defaultValue; } if (result == null) return 0; return result instanceof Number ? ((Number) result).floatValue() : Float.parseFloat((String) result); } /** * If {@link EntryValidator} is not {@code null} and {@link EntryValidator#isValid(Object)} is {@code false}, * the {@code defaultValue} will be used instead.<br> * One of these two values is then casted to a {@code double} (if it is an {@code double}) * or it is casted to a {@link String} and fed into {@link Double#parseDouble(String)} * * @return Returns one of the value as an {@code double} * * @see Double#parseDouble(String) * @see #getDefaultValue() * @see #setValue(Object) * @see #getValue() * @see #getValue(Object) * @see #getValueAsBoolean() * @see #getValueAsFloat() * @see #getValueAsInt() * @see #getValueAsLong() * @see #getValueAsString() * @see #getValueAsList() * @see #getValueAsStringList() */ public double getValueAsDouble() { Object result; if (entryValidator == null || entryValidator.isValid(this.value)) { result = this.value; } else { result = this.defaultValue; } if (result == null) return 0; return result instanceof Number ? ((Number) result).doubleValue() : Double.parseDouble((String) result); } /** * If {@link EntryValidator} is not {@code null} and {@link EntryValidator#isValid(Object)} is {@code false}, * the {@code defaultValue} will be used instead.<br> * One of these two values is then checked whether it is {@code null}, * if not {@link Object#toString()} is returned * * @return Returns one of the values {@link Object#toString()} output or {@code null} * * @see Object#toString() * @see #getDefaultValue() * @see #setValue(Object) * @see #getValue() * @see #getValue(Object) * @see #getValueAsBoolean() * @see #getValueAsDouble() * @see #getValueAsFloat() * @see #getValueAsInt() * @see #getValueAsLong() * @see #getValueAsList() * @see #getValueAsStringList() */ public @Nullable String getValueAsString() { Object result; if (entryValidator == null || entryValidator.isValid(this.value)) { result = this.value; } else { result = this.defaultValue; } return result == null ? null : result.toString(); } /** * If {@link EntryValidator} is not {@code null} and {@link EntryValidator#isValid(Object)} is {@code false}, * the {@code defaultValue} will be used instead.<br> * One of these two values is then casted to an {@link List} with {@link Object}s * * @return Returns one of the values as {@link List} or {@code null} * * @see #getDefaultValue() * @see #setValue(Object) * @see #getValue() * @see #getValue(Object) * @see #getValueAsBoolean() * @see #getValueAsDouble() * @see #getValueAsFloat() * @see #getValueAsInt() * @see #getValueAsLong() * @see #getValueAsString() * @see #getValueAsStringList() */ @SuppressWarnings("unchecked") public @Nullable List<Object> getValueAsList() { Object result; if (entryValidator == null || entryValidator.isValid(this.value)) { result = this.value; } else { result = this.defaultValue; } return (List<Object>) result; } /** * If {@link EntryValidator} is not {@code null} and {@link EntryValidator#isValid(Object)} is {@code false}, * the {@code defaultValue} will be used instead.<br> * One of these two values is then casted to an {@link List} * * @return Returns one of the values as {@link List} with {@link String}s or {@code null} * * @see Object#toString() * @see #getDefaultValue() * @see #setValue(Object) * @see #getValue() * @see #getValue(Object) * @see #getValueAsBoolean() * @see #getValueAsDouble() * @see #getValueAsFloat() * @see #getValueAsInt() * @see #getValueAsLong() * @see #getValueAsString() * @see #getValueAsList() */ @SuppressWarnings("unchecked") public @Nullable List<String> getValueAsStringList() { Object result; if (entryValidator == null || entryValidator.isValid(this.value)) { result = this.value; } else { result = this.defaultValue; } return (List<String>) result; } }
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.social.facebook.api.impl; import java.util.List; import com.fasterxml.jackson.databind.JsonNode; /** * Strategy interface for deserializing lists of data returned from Facebook as JSON. * @author Craig Walls */ interface ListDeserializer { <T> List<T> deserializeList(JsonNode jsonNode, Class<T> type); }
package top.yzhelp.campus.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; import top.yzhelp.campus.mapper.SearchRecordMapper; import top.yzhelp.campus.model.other.SearchRecord; import top.yzhelp.campus.service.SearchRecordService; /** * @author <a href="https://github.com/gongsir0630">码之泪殇</a> * @date 2021/4/8 15:54 * 你的指尖,拥有改变世界的力量 * @description 搜索历史接口实现 */ @Service public class SearchRecordServiceImpl extends ServiceImpl<SearchRecordMapper, SearchRecord> implements SearchRecordService { }
/* * MIT License * * Copyright (c) 2022 MASES s.r.l. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package microsoft.entityframeworkcore.metadata.conventions; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import microsoft.entityframeworkcore.metadata.conventions.IConvention; import microsoft.entityframeworkcore.metadata.conventions.IConventionImplementation; import microsoft.entityframeworkcore.metadata.builders.IConventionForeignKeyBuilder; import microsoft.entityframeworkcore.metadata.builders.IConventionForeignKeyBuilderImplementation; /** * The base .NET class managing Microsoft.EntityFrameworkCore.Metadata.Conventions.IForeignKeyPropertiesChangedConvention, Microsoft.EntityFrameworkCore, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/Microsoft.EntityFrameworkCore.Metadata.Conventions.IForeignKeyPropertiesChangedConvention" target="_top">https://docs.microsoft.com/en-us/dotnet/api/Microsoft.EntityFrameworkCore.Metadata.Conventions.IForeignKeyPropertiesChangedConvention</a> */ public class IForeignKeyPropertiesChangedConventionImplementation extends NetObject implements IForeignKeyPropertiesChangedConvention { /** * Fully assembly qualified name: Microsoft.EntityFrameworkCore, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60 */ public static final String assemblyFullName = "Microsoft.EntityFrameworkCore, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"; /** * Assembly name: Microsoft.EntityFrameworkCore */ public static final String assemblyShortName = "Microsoft.EntityFrameworkCore"; /** * Qualified class name: Microsoft.EntityFrameworkCore.Metadata.Conventions.IForeignKeyPropertiesChangedConvention */ public static final String className = "Microsoft.EntityFrameworkCore.Metadata.Conventions.IForeignKeyPropertiesChangedConvention"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public IForeignKeyPropertiesChangedConventionImplementation(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link IForeignKeyPropertiesChangedConvention}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link IForeignKeyPropertiesChangedConvention} instance * @throws java.lang.Throwable in case of error during cast operation */ public static IForeignKeyPropertiesChangedConvention ToIForeignKeyPropertiesChangedConvention(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new IForeignKeyPropertiesChangedConventionImplementation(from.getJCOInstance()); } // Methods section // Properties section // Instance Events section }
/* * Copyright 2013-2016 Netherlands Forensic Institute * * 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.parsingdata.metal.expression.value.reference; import java.util.Optional; import io.parsingdata.metal.Util; import io.parsingdata.metal.data.ImmutableList; import io.parsingdata.metal.data.ParseGraph; import io.parsingdata.metal.encoding.Encoding; import io.parsingdata.metal.expression.value.Value; import io.parsingdata.metal.expression.value.ValueExpression; /** * A {@link ValueExpression} that represents the * {@link io.parsingdata.metal.expression.value.Value} most recently added to * the parse state. */ public class Self implements ValueExpression { @Override public ImmutableList<Optional<Value>> eval(final ParseGraph graph, final Encoding encoding) { return ImmutableList.create(Optional.of(graph.current())); } @Override public String toString() { return getClass().getSimpleName(); } @Override public boolean equals(final Object obj) { return Util.notNullAndSameClass(this, obj); } @Override public int hashCode() { return 2; } }
/* * Copyright (c) 2020, The Magma Authors * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * * 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.openschema.mma.backend.request; import com.google.gson.annotations.SerializedName; /** * Class with the structure expected to be received in the OpenSchema's middle box registration API. */ public class RegisterRequest { @SerializedName("uuid") private String mUUID; public RegisterRequest(String uuid) { mUUID = uuid; } }
/* * Bitcoin cryptography library * Copyright (c) Project Nayuki * * https://www.nayuki.io/page/bitcoin-cryptography-library * https://github.com/nayuki/Bitcoin-Cryptography-Library */ //MIT license package money.terra.terrawallet.library; import static java.lang.Integer.rotateLeft; import java.util.Arrays; import java.util.Objects; /** * Computes the RIPEMD-160 hash of an array of bytes. Not instantiable. */ public final class Ripemd160 { private static final int BLOCK_LEN = 64; // In bytes /*---- Static functions ----*/ /** * Computes and returns a 20-byte (160-bit) hash of the specified binary message. * Each call will return a new byte array object instance. * @param msg the message to compute the hash of * @return a 20-byte array representing the message's RIPEMD-160 hash * @throws NullPointerException if the message is {@code null} */ public static byte[] getHash(byte[] msg) { // Compress whole message blocks Objects.requireNonNull(msg); int[] state = {0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0}; int off = msg.length / BLOCK_LEN * BLOCK_LEN; compress(state, msg, off); // Final blocks, padding, and length byte[] block = new byte[BLOCK_LEN]; System.arraycopy(msg, off, block, 0, msg.length - off); off = msg.length % block.length; block[off] = (byte)0x80; off++; if (off + 8 > block.length) { compress(state, block, block.length); Arrays.fill(block, (byte)0); } long len = (long)msg.length << 3; for (int i = 0; i < 8; i++) block[block.length - 8 + i] = (byte)(len >>> (i * 8)); compress(state, block, block.length); // Int32 array to bytes in little endian byte[] result = new byte[state.length * 4]; for (int i = 0; i < result.length; i++) result[i] = (byte)(state[i / 4] >>> (i % 4 * 8)); return result; } /*---- Private functions ----*/ private static void compress(int[] state, byte[] blocks, int len) { if (len % BLOCK_LEN != 0) throw new IllegalArgumentException(); for (int i = 0; i < len; i += BLOCK_LEN) { // Message schedule int[] schedule = new int[16]; for (int j = 0; j < BLOCK_LEN; j++) schedule[j / 4] |= (blocks[i + j] & 0xFF) << (j % 4 * 8); // The 80 rounds int al = state[0], ar = state[0]; int bl = state[1], br = state[1]; int cl = state[2], cr = state[2]; int dl = state[3], dr = state[3]; int el = state[4], er = state[4]; for (int j = 0; j < 80; j++) { int temp; temp = rotateLeft(al + f(j, bl, cl, dl) + schedule[RL[j]] + KL[j / 16], SL[j]) + el; al = el; el = dl; dl = rotateLeft(cl, 10); cl = bl; bl = temp; temp = rotateLeft(ar + f(79 - j, br, cr, dr) + schedule[RR[j]] + KR[j / 16], SR[j]) + er; ar = er; er = dr; dr = rotateLeft(cr, 10); cr = br; br = temp; } int temp = state[1] + cl + dr; state[1] = state[2] + dl + er; state[2] = state[3] + el + ar; state[3] = state[4] + al + br; state[4] = state[0] + bl + cr; state[0] = temp; } } private static int f(int i, int x, int y, int z) { assert 0 <= i && i < 80; if (i < 16) return x ^ y ^ z; if (i < 32) return (x & y) | (~x & z); if (i < 48) return (x | ~y) ^ z; if (i < 64) return (x & z) | (y & ~z); return x ^ (y | ~z); } /*---- Class constants ----*/ private static final int[] KL = {0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E}; // Round constants for left line private static final int[] KR = {0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000}; // Round constants for right line private static final int[] RL = { // Message schedule for left line 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13}; private static final int[] RR = { // Message schedule for right line 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11}; private static final int[] SL = { // Left-rotation for left line 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6}; private static final int[] SR = { // Left-rotation for right line 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11}; }
/*************************************************************************** * Copyright 2020 Kieker Project (http://kieker-monitoring.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ package kieker.analysis.util.time; import java.time.temporal.ChronoUnit; import java.util.function.Function; /** * This class is a {@link Function} that maps {@link ChronoUnit}s to their common symbols and abbreviations. If not common abbreviations exists a full name is * returned. * * @author Sören Henning * * @since 1.14 */ public final class ChronoUnitToSymbolMapper implements Function<ChronoUnit, String> { // NOPMD (switch statement leads to long class) private ChronoUnitToSymbolMapper() {} @Override public String apply(final ChronoUnit chronoUnit) { // NOPMD (switch statement leads to long method) switch (chronoUnit) { case NANOS: return "ns"; case MICROS: return "�s"; case MILLIS: return "ms"; case SECONDS: return "s"; case MINUTES: return "min"; case HOURS: return "h"; case DAYS: return "d"; case YEARS: return "a"; case WEEKS: return "weeks"; case CENTURIES: return "centuries"; case DECADES: return "decades"; case ERAS: return "eras"; case FOREVER: return "forever"; case HALF_DAYS: return "half days"; case MILLENNIA: return "millennia"; case MONTHS: return "months"; default: throw new IllegalArgumentException("Unknown ChronoUnit constant"); } } public static ChronoUnitToSymbolMapper create() { return new ChronoUnitToSymbolMapper(); } }
package com.snk.system.service; import java.util.List; import com.snk.system.domain.SysNotice; /** * 公告 服务层 * * @author snk */ public interface ISysNoticeService { /** * 查询公告信息 * * @param noticeId 公告ID * @return 公告信息 */ public SysNotice selectNoticeById(Long noticeId); /** * 查询公告列表 * * @param notice 公告信息 * @return 公告集合 */ public List<SysNotice> selectNoticeList(SysNotice notice); /** * 新增公告 * * @param notice 公告信息 * @return 结果 */ public int insertNotice(SysNotice notice); /** * 修改公告 * * @param notice 公告信息 * @return 结果 */ public int updateNotice(SysNotice notice); /** * 删除公告信息 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteNoticeByIds(String ids); }
/* * 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. * * Copyright 2012-2022 the original author or authors. */ package org.assertj.core.api.bytearray; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assumptions.assumeThat; import static org.assertj.core.test.ErrorMessagesForTest.shouldBeEqualMessage; import static org.assertj.core.util.AssertionsUtil.expectAssertionError; import static org.assertj.core.util.AssertionsUtil.expectAssumptionNotMetException; import static org.assertj.core.util.FailureMessages.actualIsNull; import java.nio.charset.Charset; import org.assertj.core.api.SoftAssertions; import org.assertj.core.error.AssertJMultipleFailuresError; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; @DisplayName("ByteArrayAssert asString") class ByteArrayAssert_asString_with_charset_Test { private static final Charset TURKISH_CHARSET = Charset.forName("windows-1254"); @Test void should_convert_bytes_array_to_a_proper_string_with_specific_encoding() { // GIVEN String real = "Gerçek"; byte[] bytes = real.getBytes(TURKISH_CHARSET); // WHEN/THEN assertThat(bytes).asString(TURKISH_CHARSET) .isEqualTo(real); } @Test void should_fail_if_actual_is_null() { // GIVEN byte[] bytes = null; // WHEN AssertionError error = expectAssertionError(() -> assertThat(bytes).asString(TURKISH_CHARSET)); // THEN assertThat(error).hasMessage(actualIsNull()); } @Test void should_fail_if_actual_does_not_match() { // GIVEN String real = "Gerçek"; byte[] bytes = real.getBytes(TURKISH_CHARSET); // WHEN AssertionError assertionError = expectAssertionError(() -> assertThat(bytes).asString(TURKISH_CHARSET).isEqualTo("bar")); // THEN assertThat(assertionError).hasMessage(shouldBeEqualMessage("\"Gerçek\"", "\"bar\"")) .isExactlyInstanceOf(AssertionFailedError.class); } @Test void should_pass_with_soft_assertions() { // GIVEN SoftAssertions softly = new SoftAssertions(); String real = "Gerçek"; byte[] bytes = real.getBytes(TURKISH_CHARSET); // WHEN/THEN softly.assertThat(bytes).asString(TURKISH_CHARSET).isEqualTo(real); softly.assertAll(); } @Test void should_fail_with_soft_assertions_capturing_all_errors() { // GIVEN SoftAssertions softly = new SoftAssertions(); String real = "Gerçek"; byte[] bytes = real.getBytes(TURKISH_CHARSET); // WHEN softly.assertThat(bytes) .asString(TURKISH_CHARSET) .isEqualTo("bar") .isBlank(); AssertionError assertionError = expectAssertionError(softly::assertAll); // THEN assertThat(assertionError).hasMessageContainingAll("Multiple Failures (2 failures)", "-- failure 1 --", shouldBeEqualMessage("\"Gerçek\"", "\"bar\""), "-- failure 2 --", "Expecting blank but was: \"Gerçek\"") .isExactlyInstanceOf(AssertJMultipleFailuresError.class); } @Test void should_ignore_test_when_assumption_for_internally_created_hex_string_assertion_fails() { // GIVEN String real = "Gerçek"; byte[] bytes = real.getBytes(TURKISH_CHARSET); // WHEN/THEN expectAssumptionNotMetException(() -> assumeThat(bytes).asString(TURKISH_CHARSET).isEqualTo("bar")); } @Test void should_run_test_when_assumption_for_internally_created_string_passes() { // GIVEN String real = "Gerçek"; byte[] bytes = real.getBytes(TURKISH_CHARSET); // WHEN/THEN assertThatCode(() -> assumeThat(bytes).asString(TURKISH_CHARSET).startsWith("Gerç")).doesNotThrowAnyException(); } }
package io.agent.hooks; import io.agent.annotations.After; import io.agent.annotations.Before; import io.agent.annotations.Hook; import io.agent.hookcontext.MetricDef; import io.agent.hookcontext.MetricsStore; import io.prometheus.client.Counter; import io.prometheus.client.Summary; import java.util.concurrent.TimeUnit; import static io.agent.hooks.HttpContext.HTTP_METHOD; import static io.agent.hooks.HttpContext.HTTP_PATH; @Hook(instruments = { "java.sql.Statement", "java.sql.Connection" }) public class JdbcHook { private final Counter sqlQueriesTotal; private final Summary sqlQueriesDuration; private long startTime = 0; public JdbcHook(MetricsStore metricsStore) { sqlQueriesTotal = metricsStore.createOrGet(new MetricDef<>( "sql_queries_total", (name, registry) -> Counter.build() .name(name) .labelNames("method", "path", "query") .help("Total number of sql queries.") .register(registry) )); sqlQueriesDuration = metricsStore.createOrGet(new MetricDef<>( "sql_query_duration", (name, registry) -> Summary.build() .quantile(0.5, 0.05) // Add 50th percentile (= median) with 5% tolerated error .quantile(0.9, 0.01) // Add 90th percentile with 1% tolerated error .quantile(0.99, 0.001) // Add 99th percentile with 0.1% tolerated error .name(name) .labelNames("method", "path", "query") .help("Duration for serving the sql queries in seconds.") .register(registry) )); } private String stripValues(String query) { // We want the structure of the query as labels, not the actual values. // Therefore, we replace: // insert into Member (id, name, email, phone_number) values (0, 'John Smith', 'john.smith@mailinator.com', '2125551212') // with // insert into Member (id, name, email, phone_number) values (...) return query.replaceAll("values\\s*\\(.*?\\)", "values (...)"); } // --- before @Before(method = {"execute", "executeQuery", "executeUpdate", "executeLargeUpdate", "prepareStatement", "prepareCall"}) public void before(String sql) { startTime = System.nanoTime(); } @Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, int autoGeneratedKeys) { before(sql); } @Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, int[] columnIndexes) { before(sql); } @Before(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void before(String sql, String[] columnNames) { before(sql); } @Before(method = {"prepareStatement", "prepareCall"}) public void before(String sql, int resultSetType, int resultSetConcurrency) { before(sql); } @Before(method = {"prepareStatement", "prepareCall"}) public void before(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) { before(sql); } // --- after @After(method = {"execute", "executeQuery", "executeUpdate", "executeLargeUpdate", "prepareStatement", "prepareCall"}) public void after(String sql) throws Exception { double duration = ((double) System.nanoTime() - startTime) / (double) TimeUnit.SECONDS.toNanos(1L); String method = HttpContext.get(HTTP_METHOD).orElse("no http context"); String path = HttpContext.get(HTTP_PATH).orElse("no http context"); String query = stripValues(sql); sqlQueriesTotal.labels(method, path, query).inc(); sqlQueriesDuration.labels(method, path, query).observe(duration); } @After(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void after(String sql, int autoGeneratedKeys) throws Exception { after(sql); } @After(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void after(String sql, int[] columnIndexes) throws Exception { after(sql); } @After(method = {"execute", "executeUpdate", "executeLargeUpdate", "prepareStatement"}) public void after(String sql, String[] columnNames) throws Exception { after(sql); } @After(method = {"prepareStatement", "prepareCall"}) public void after(String sql, int resultSetType, int resultSetConcurrency) throws Exception { after(sql); } @After(method = {"prepareStatement", "prepareCall"}) public void after(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws Exception { after(sql); } }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.resource; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.mock.web.test.MockServletContext; import org.springframework.util.StringUtils; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.accept.ContentNegotiationManagerFactoryBean; import org.springframework.web.servlet.HandlerMapping; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Unit tests for {@link ResourceHttpRequestHandler}. * * @author Keith Donald * @author Jeremy Grelle * @author Rossen Stoyanchev * @author Brian Clozel */ public class ResourceHttpRequestHandlerTests { private ResourceHttpRequestHandler handler; private MockHttpServletRequest request; private MockHttpServletResponse response; @BeforeEach public void setup() throws Exception { List<Resource> paths = new ArrayList<>(2); paths.add(new ClassPathResource("test/", getClass())); paths.add(new ClassPathResource("testalternatepath/", getClass())); paths.add(new ClassPathResource("META-INF/resources/webjars/")); this.handler = new ResourceHttpRequestHandler(); this.handler.setLocations(paths); this.handler.setCacheSeconds(3600); this.handler.setServletContext(new TestServletContext()); this.handler.afterPropertiesSet(); this.request = new MockHttpServletRequest("GET", ""); this.response = new MockHttpServletResponse(); } @Test public void getResource() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getContentType()).isEqualTo("text/css"); assertThat(this.response.getContentLength()).isEqualTo(17); assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600"); assertThat(this.response.containsHeader("Last-Modified")).isTrue(); assertThat(this.response.getDateHeader("Last-Modified") / 1000) .isEqualTo(resourceLastModified("test/foo.css") / 1000); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }"); } @Test public void getResourceHttpHeader() throws Exception { this.request.setMethod("HEAD"); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(200); assertThat(this.response.getContentType()).isEqualTo("text/css"); assertThat(this.response.getContentLength()).isEqualTo(17); assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600"); assertThat(this.response.containsHeader("Last-Modified")).isTrue(); assertThat(this.response.getDateHeader("Last-Modified") / 1000) .isEqualTo(resourceLastModified("test/foo.css") / 1000); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); assertThat(this.response.getContentAsByteArray().length).isEqualTo(0); } @Test public void getResourceHttpOptions() throws Exception { this.request.setMethod("OPTIONS"); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(200); assertThat(this.response.getHeader("Allow")).isEqualTo("GET,HEAD,OPTIONS"); } @Test public void getResourceNoCache() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.handler.setCacheSeconds(0); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getHeader("Cache-Control")).isEqualTo("no-store"); assertThat(this.response.containsHeader("Last-Modified")).isTrue(); assertThat(this.response.getDateHeader("Last-Modified") / 1000) .isEqualTo(resourceLastModified("test/foo.css") / 1000); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test public void getVersionedResource() throws Exception { VersionResourceResolver versionResolver = new VersionResourceResolver().addFixedVersionStrategy("versionString", "/**"); this.handler.setResourceResolvers(Arrays.asList(versionResolver, new PathResourceResolver())); this.handler.afterPropertiesSet(); this.request.setAttribute( HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "versionString/foo.css"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getHeader("ETag")).isEqualTo("\"versionString\""); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @SuppressWarnings("deprecation") public void getResourceHttp10BehaviorCache() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.handler.setCacheSeconds(3600); this.handler.setUseExpiresHeader(true); this.handler.setUseCacheControlHeader(true); this.handler.setAlwaysMustRevalidate(true); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600, must-revalidate"); assertThat( this.response.getDateHeader("Expires") >= System.currentTimeMillis() - 1000 + (3600 * 1000)) .isTrue(); assertThat(this.response.containsHeader("Last-Modified")).isTrue(); assertThat(this.response.getDateHeader("Last-Modified") / 1000) .isEqualTo(resourceLastModified("test/foo.css") / 1000); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test @SuppressWarnings("deprecation") public void getResourceHttp10BehaviorNoCache() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.handler.setCacheSeconds(0); this.handler.setUseExpiresHeader(true); this.handler.setUseCacheControlNoStore(false); this.handler.setUseCacheControlHeader(true); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getHeader("Pragma")).isEqualTo("no-cache"); assertThat(this.response.getHeaderValues("Cache-Control")).hasSize(1); assertThat(this.response.getHeader("Cache-Control")).isEqualTo("no-cache"); assertThat(this.response.getDateHeader("Expires") <= System.currentTimeMillis()).isTrue(); assertThat(this.response.containsHeader("Last-Modified")).isTrue(); assertThat(this.response.getDateHeader("Last-Modified") / 1000) .isEqualTo(resourceLastModified("test/foo.css") / 1000); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test public void getResourceWithHtmlMediaType() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.html"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getContentType()).isEqualTo("text/html"); assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600"); assertThat(this.response.containsHeader("Last-Modified")).isTrue(); assertThat(this.response.getDateHeader("Last-Modified") / 1000) .isEqualTo(resourceLastModified("test/foo.html") / 1000); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test public void getResourceFromAlternatePath() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "baz.css"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getContentType()).isEqualTo("text/css"); assertThat(this.response.getContentLength()).isEqualTo(17); assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600"); assertThat(this.response.containsHeader("Last-Modified")).isTrue(); assertThat(this.response.getDateHeader("Last-Modified") / 1000) .isEqualTo(resourceLastModified("testalternatepath/baz.css") / 1000); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }"); } @Test public void getResourceFromSubDirectory() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "js/foo.js"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getContentType()).isEqualTo("text/javascript"); assertThat(this.response.getContentAsString()) .isEqualTo("function foo() { console.log(\"hello world\"); }"); } @Test public void getResourceFromSubDirectoryOfAlternatePath() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "js/baz.js"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getContentType()).isEqualTo("text/javascript"); assertThat(this.response.getContentAsString()) .isEqualTo("function foo() { console.log(\"hello world\"); }"); } @Test // SPR-13658 public void getResourceWithRegisteredMediaType() throws Exception { ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean(); factory.addMediaType("bar", new MediaType("foo", "bar")); factory.afterPropertiesSet(); ContentNegotiationManager manager = factory.getObject(); List<Resource> paths = Collections.singletonList(new ClassPathResource("test/", getClass())); ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler(); handler.setServletContext(new MockServletContext()); handler.setLocations(paths); handler.setContentNegotiationManager(manager); handler.afterPropertiesSet(); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.bar"); handler.handleRequest(this.request, this.response); assertThat(this.response.getContentType()).isEqualTo("foo/bar"); assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }"); } @Test // SPR-14577 public void getMediaTypeWithFavorPathExtensionOff() throws Exception { ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean(); factory.setFavorPathExtension(false); factory.afterPropertiesSet(); ContentNegotiationManager manager = factory.getObject(); List<Resource> paths = Collections.singletonList(new ClassPathResource("test/", getClass())); ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler(); handler.setServletContext(new MockServletContext()); handler.setLocations(paths); handler.setContentNegotiationManager(manager); handler.afterPropertiesSet(); this.request.addHeader("Accept", "application/json,text/plain,*/*"); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.html"); handler.handleRequest(this.request, this.response); assertThat(this.response.getContentType()).isEqualTo("text/html"); } @Test // SPR-14368 public void getResourceWithMediaTypeResolvedThroughServletContext() throws Exception { MockServletContext servletContext = new MockServletContext() { @Override public String getMimeType(String filePath) { return "foo/bar"; } @Override public String getVirtualServerName() { return ""; } }; List<Resource> paths = Collections.singletonList(new ClassPathResource("test/", getClass())); ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler(); handler.setServletContext(servletContext); handler.setLocations(paths); handler.afterPropertiesSet(); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); handler.handleRequest(this.request, this.response); assertThat(this.response.getContentType()).isEqualTo("foo/bar"); assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }"); } @Test public void testInvalidPath() throws Exception { // Use mock ResourceResolver: i.e. we're only testing upfront validations... Resource resource = mock(Resource.class); given(resource.getFilename()).willThrow(new AssertionError("Resource should not be resolved")); given(resource.getInputStream()) .willThrow(new AssertionError("Resource should not be resolved")); ResourceResolver resolver = mock(ResourceResolver.class); given(resolver.resolveResource(any(), any(), any(), any())).willReturn(resource); ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler(); handler.setLocations(Collections.singletonList(new ClassPathResource("test/", getClass()))); handler.setResourceResolvers(Collections.singletonList(resolver)); handler.setServletContext(new TestServletContext()); handler.afterPropertiesSet(); testInvalidPath("../testsecret/secret.txt", handler); testInvalidPath("test/../../testsecret/secret.txt", handler); testInvalidPath(":/../../testsecret/secret.txt", handler); Resource location = new UrlResource(getClass().getResource("./test/")); this.handler.setLocations(Collections.singletonList(location)); Resource secretResource = new UrlResource(getClass().getResource("testsecret/secret.txt")); String secretPath = secretResource.getURL().getPath(); testInvalidPath("file:" + secretPath, handler); testInvalidPath("/file:" + secretPath, handler); testInvalidPath("url:" + secretPath, handler); testInvalidPath("/url:" + secretPath, handler); testInvalidPath("/../.." + secretPath, handler); testInvalidPath("/%2E%2E/testsecret/secret.txt", handler); testInvalidPath("/%2E%2E/testsecret/secret.txt", handler); testInvalidPath("%2F%2F%2E%2E%2F%2F%2E%2E" + secretPath, handler); } private void testInvalidPath(String requestPath, ResourceHttpRequestHandler handler) throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, requestPath); this.response = new MockHttpServletResponse(); handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @Test public void resolvePathWithTraversal() throws Exception { for (HttpMethod method : HttpMethod.values()) { this.request = new MockHttpServletRequest("GET", ""); this.response = new MockHttpServletResponse(); testResolvePathWithTraversal(method); } } private void testResolvePathWithTraversal(HttpMethod httpMethod) throws Exception { this.request.setMethod(httpMethod.name()); Resource location = new ClassPathResource("test/", getClass()); this.handler.setLocations(Collections.singletonList(location)); testResolvePathWithTraversal(location, "../testsecret/secret.txt"); testResolvePathWithTraversal(location, "test/../../testsecret/secret.txt"); testResolvePathWithTraversal(location, ":/../../testsecret/secret.txt"); location = new UrlResource(getClass().getResource("./test/")); this.handler.setLocations(Collections.singletonList(location)); Resource secretResource = new UrlResource(getClass().getResource("testsecret/secret.txt")); String secretPath = secretResource.getURL().getPath(); testResolvePathWithTraversal(location, "file:" + secretPath); testResolvePathWithTraversal(location, "/file:" + secretPath); testResolvePathWithTraversal(location, "url:" + secretPath); testResolvePathWithTraversal(location, "/url:" + secretPath); testResolvePathWithTraversal(location, "/" + secretPath); testResolvePathWithTraversal(location, "////../.." + secretPath); testResolvePathWithTraversal(location, "/%2E%2E/testsecret/secret.txt"); testResolvePathWithTraversal(location, "%2F%2F%2E%2E%2F%2Ftestsecret/secret.txt"); testResolvePathWithTraversal(location, "/ " + secretPath); } private void testResolvePathWithTraversal(Resource location, String requestPath) throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, requestPath); this.response = new MockHttpServletResponse(); this.handler.handleRequest(this.request, this.response); if (!location.createRelative(requestPath).exists() && !requestPath.contains(":")) { fail(requestPath + " doesn't actually exist as a relative path"); } assertThat(this.response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @Test public void ignoreInvalidEscapeSequence() throws Exception { this.request.setAttribute( HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/%foo%/bar.txt"); this.response = new MockHttpServletResponse(); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(404); } @Test public void processPath() { // Unchanged assertThat(this.handler.processPath("/foo/bar")).isSameAs("/foo/bar"); assertThat(this.handler.processPath("foo/bar")).isSameAs("foo/bar"); // leading whitespace control characters (00-1F) assertThat(this.handler.processPath(" /foo/bar")).isEqualTo("/foo/bar"); assertThat(this.handler.processPath((char) 1 + "/foo/bar")).isEqualTo("/foo/bar"); assertThat(this.handler.processPath((char) 31 + "/foo/bar")).isEqualTo("/foo/bar"); assertThat(this.handler.processPath(" foo/bar")).isEqualTo("foo/bar"); assertThat(this.handler.processPath((char) 31 + "foo/bar")).isEqualTo("foo/bar"); // leading control character 0x7F (DEL) assertThat(this.handler.processPath((char) 127 + "/foo/bar")).isEqualTo("/foo/bar"); assertThat(this.handler.processPath((char) 127 + "/foo/bar")).isEqualTo("/foo/bar"); // leading control and '/' characters assertThat(this.handler.processPath(" / foo/bar")).isEqualTo("/foo/bar"); assertThat(this.handler.processPath(" / / foo/bar")).isEqualTo("/foo/bar"); assertThat(this.handler.processPath(" // /// //// foo/bar")).isEqualTo("/foo/bar"); assertThat(this.handler.processPath((char) 1 + " / " + (char) 127 + " // foo/bar")) .isEqualTo("/foo/bar"); // root or empty path assertThat(this.handler.processPath(" ")).isEqualTo(""); assertThat(this.handler.processPath("/")).isEqualTo("/"); assertThat(this.handler.processPath("///")).isEqualTo("/"); assertThat(this.handler.processPath("/ / / ")).isEqualTo("/"); assertThat(this.handler.processPath("\\/ \\/ \\/ ")).isEqualTo("/"); // duplicate slash or backslash assertThat(this.handler.processPath("//foo/ /bar//baz//")).isEqualTo("/foo/ /bar/baz/"); assertThat(this.handler.processPath("\\\\foo\\ \\bar\\\\baz\\\\")).isEqualTo("/foo/ /bar/baz/"); assertThat(this.handler.processPath("foo\\\\/\\////bar")).isEqualTo("foo/bar"); } @Test public void initAllowedLocations() { PathResourceResolver resolver = (PathResourceResolver) this.handler.getResourceResolvers().get(0); Resource[] locations = resolver.getAllowedLocations(); assertThat(locations.length).isEqualTo(3); assertThat(((ClassPathResource) locations[0]).getPath()).isEqualTo("test/"); assertThat(((ClassPathResource) locations[1]).getPath()).isEqualTo("testalternatepath/"); assertThat(((ClassPathResource) locations[2]).getPath()) .isEqualTo("META-INF/resources/webjars/"); } @Test public void initAllowedLocationsWithExplicitConfiguration() throws Exception { ClassPathResource location1 = new ClassPathResource("test/", getClass()); ClassPathResource location2 = new ClassPathResource("testalternatepath/", getClass()); PathResourceResolver pathResolver = new PathResourceResolver(); pathResolver.setAllowedLocations(location1); ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler(); handler.setResourceResolvers(Collections.singletonList(pathResolver)); handler.setServletContext(new MockServletContext()); handler.setLocations(Arrays.asList(location1, location2)); handler.afterPropertiesSet(); Resource[] locations = pathResolver.getAllowedLocations(); assertThat(locations.length).isEqualTo(1); assertThat(((ClassPathResource) locations[0]).getPath()).isEqualTo("test/"); } @Test public void notModified() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.request.addHeader("If-Modified-Since", resourceLastModified("test/foo.css")); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_NOT_MODIFIED); } @Test public void modified() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.request.addHeader( "If-Modified-Since", resourceLastModified("test/foo.css") / 1000 * 1000 - 1); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }"); } @Test public void directory() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "js/"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(404); } @Test public void directoryInJarFile() throws Exception { this.request.setAttribute( HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "underscorejs/"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(404); } @Test public void missingResourcePath() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, ""); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(404); } @Test public void noPathWithinHandlerMappingAttribute() throws Exception { assertThatIllegalStateException() .isThrownBy(() -> this.handler.handleRequest(this.request, this.response)); } @Test public void unsupportedHttpMethod() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.request.setMethod("POST"); assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class) .isThrownBy(() -> this.handler.handleRequest(this.request, this.response)); } @Test public void resourceNotFound() throws Exception { for (HttpMethod method : HttpMethod.values()) { this.request = new MockHttpServletRequest("GET", ""); this.response = new MockHttpServletResponse(); resourceNotFound(method); } } private void resourceNotFound(HttpMethod httpMethod) throws Exception { this.request.setMethod(httpMethod.name()); this.request.setAttribute( HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "not-there.css"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value()); } @Test public void partialContentByteRange() throws Exception { this.request.addHeader("Range", "bytes=0-1"); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(206); assertThat(this.response.getContentType()).isEqualTo("text/plain"); assertThat(this.response.getContentLength()).isEqualTo(2); assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 0-1/10"); assertThat(this.response.getContentAsString()).isEqualTo("So"); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test public void partialContentByteRangeNoEnd() throws Exception { this.request.addHeader("Range", "bytes=9-"); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(206); assertThat(this.response.getContentType()).isEqualTo("text/plain"); assertThat(this.response.getContentLength()).isEqualTo(1); assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 9-9/10"); assertThat(this.response.getContentAsString()).isEqualTo("."); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test public void partialContentByteRangeLargeEnd() throws Exception { this.request.addHeader("Range", "bytes=9-10000"); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(206); assertThat(this.response.getContentType()).isEqualTo("text/plain"); assertThat(this.response.getContentLength()).isEqualTo(1); assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 9-9/10"); assertThat(this.response.getContentAsString()).isEqualTo("."); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test public void partialContentSuffixRange() throws Exception { this.request.addHeader("Range", "bytes=-1"); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(206); assertThat(this.response.getContentType()).isEqualTo("text/plain"); assertThat(this.response.getContentLength()).isEqualTo(1); assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 9-9/10"); assertThat(this.response.getContentAsString()).isEqualTo("."); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test public void partialContentSuffixRangeLargeSuffix() throws Exception { this.request.addHeader("Range", "bytes=-11"); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(206); assertThat(this.response.getContentType()).isEqualTo("text/plain"); assertThat(this.response.getContentLength()).isEqualTo(10); assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes 0-9/10"); assertThat(this.response.getContentAsString()).isEqualTo("Some text."); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test public void partialContentInvalidRangeHeader() throws Exception { this.request.addHeader("Range", "bytes= foo bar"); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(416); assertThat(this.response.getHeader("Content-Range")).isEqualTo("bytes */10"); assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes"); assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1); } @Test public void partialContentMultipleByteRanges() throws Exception { this.request.addHeader("Range", "bytes=0-1, 4-5, 8-9"); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.txt"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getStatus()).isEqualTo(206); assertThat(this.response.getContentType().startsWith("multipart/byteranges; boundary=")) .isTrue(); String boundary = "--" + this.response.getContentType().substring(31); String content = this.response.getContentAsString(); String[] ranges = StringUtils.tokenizeToStringArray(content, "\r\n", false, true); assertThat(ranges[0]).isEqualTo(boundary); assertThat(ranges[1]).isEqualTo("Content-Type: text/plain"); assertThat(ranges[2]).isEqualTo("Content-Range: bytes 0-1/10"); assertThat(ranges[3]).isEqualTo("So"); assertThat(ranges[4]).isEqualTo(boundary); assertThat(ranges[5]).isEqualTo("Content-Type: text/plain"); assertThat(ranges[6]).isEqualTo("Content-Range: bytes 4-5/10"); assertThat(ranges[7]).isEqualTo(" t"); assertThat(ranges[8]).isEqualTo(boundary); assertThat(ranges[9]).isEqualTo("Content-Type: text/plain"); assertThat(ranges[10]).isEqualTo("Content-Range: bytes 8-9/10"); assertThat(ranges[11]).isEqualTo("t."); } @Test // SPR-14005 public void doOverwriteExistingCacheControlHeaders() throws Exception { this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.css"); this.response.setHeader("Cache-Control", "no-store"); this.handler.handleRequest(this.request, this.response); assertThat(this.response.getHeader("Cache-Control")).isEqualTo("max-age=3600"); } private long resourceLastModified(String resourceName) throws IOException { return new ClassPathResource(resourceName, getClass()).getFile().lastModified(); } private static class TestServletContext extends MockServletContext { @Override public String getMimeType(String filePath) { if (filePath.endsWith(".css")) { return "text/css"; } else if (filePath.endsWith(".js")) { return "text/javascript"; } else { return super.getMimeType(filePath); } } } }
package com.bornium.infrastructurebootstrapping.crypto.services; import com.bornium.infrastructurebootstrapping.base.services.execution.docker.ContainerShell; import com.bornium.infrastructurebootstrapping.base.services.execution.docker.DockerService; import com.bornium.infrastructurebootstrapping.crypto.services.openssl.OpenSSLExtension; import com.bornium.infrastructurebootstrapping.crypto.services.openssl.SAN; import com.bornium.infrastructurebootstrapping.crypto.services.openssl.X509Subject; import org.springframework.stereotype.Service; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.function.Consumer; @Service public class OpenSSLService { boolean debug = true; final DockerService dockerService; public OpenSSLService(DockerService dockerService) { this.dockerService = dockerService; } public void doWithOpenSSL(Consumer<ContainerShell> run) { dockerService.doInContainerFromDirectory("src/main/resources/files/docker/openssl/", (shell) -> { // this should actually be mounted into the container to preserve those files // currently those are created on the fly in the container shell.run("mkdir certs"); shell.run("mkdir crl"); shell.run("mkdir newcerts"); shell.run("touch index.txt"); shell.run("touch serial && echo '01' >> serial"); run.accept(shell); }); } Path templateConfig(Path csrConfig, X509Subject subject, SAN san) { try { String content = new String(Files.readAllBytes(csrConfig)); Path temp = Files.createTempFile("ib", ".conf"); content = replaceSAN(san, replaceSubject(subject, content)); // if (debug) // System.out.println(content); Files.write(temp, content.getBytes()); temp.toFile().deleteOnExit(); return temp; } catch (IOException e) { throw new RuntimeException(e); } } private String replaceSubject(X509Subject subject, String content) { if (subject == null || subject.toOpenSSLConfig().isEmpty()) return content.replace("[ req_distinguished_name ]", "").replace("${subject}", ""); return content .replace("${subject}", subject.toOpenSSLConfig()); } private String replaceSAN(SAN san, String contentNew) { if (san == null || san.toOpenSSLConfig().isEmpty()) return contentNew .replace("[ alt_names ]", "") .replace("${san}", "") .replace("req_extensions = req_ext", ""); return contentNew.replace("${san}", san.toOpenSSLConfig()); } public void createPrivateKey(Path destination, int strength) { doWithOpenSSL((shell) -> { System.out.println(shell.run("openssl genrsa -out private.pem " + strength)); System.out.println(dockerService.getFrom(shell.getContainerName(), "/private.pem", destination.toString())); }); } public void createCsr(Path privateKey, Path config, X509Subject subject, SAN san, Path destination) { doWithOpenSSL(shell -> { System.out.println(dockerService.putInto(shell.getContainerName(), privateKey.toString(), "/private.pem")); System.out.println(dockerService.putInto(shell.getContainerName(), templateConfig(config, subject, san).toString(), "/openssl.conf")); System.out.println(shell.run("openssl req -new -key private.pem -out cert.csr -config openssl.conf")); if (debug) System.out.println(shell.run("openssl req -in cert.csr -noout -text")); System.out.println(dockerService.getFrom(shell.getContainerName(), "/cert.csr", destination.toString())); }); } public void createSelfSignedCert(Path privateKey, Path config, X509Subject subject, SAN san, OpenSSLExtension extension, Path destination) { doWithOpenSSL(shell -> { System.out.println(dockerService.putInto(shell.getContainerName(), privateKey.toString(), "/private.pem")); System.out.println(dockerService.putInto(shell.getContainerName(), templateConfig(config, subject, san).toString(), "/openssl.conf")); System.out.println(shell.run("openssl req -extensions " + extension.getValue() + " -new -x509 -key private.pem -out cert.pem -config openssl.conf")); if (debug) System.out.println(shell.run("openssl x509 -in cert.pem -noout -text")); System.out.println(dockerService.getFrom(shell.getContainerName(), "/cert.pem", destination.toString())); }); } public void signCsr(Path privateKey, Path cert, Path config, X509Subject subject, SAN san, Path csr, OpenSSLExtension extension, Path destination) { doWithOpenSSL(shell -> { System.out.println(dockerService.putInto(shell.getContainerName(), privateKey.toString(), "/ca-key.pem")); System.out.println(dockerService.putInto(shell.getContainerName(), cert.toString(), "/ca-cert.pem")); System.out.println(dockerService.putInto(shell.getContainerName(), templateConfig(config, subject, san).toString(), "/openssl.conf")); System.out.println(dockerService.putInto(shell.getContainerName(), csr.toString(), "/cert.csr")); System.out.println(shell.run("openssl x509 -req -in cert.csr -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem -sha256 -days 375 -extfile openssl.conf -extensions " + extension.getValue())); if (debug) System.out.println(shell.run("openssl x509 -in cert.pem -noout -text")); System.out.println(dockerService.getFrom(shell.getContainerName(), "/cert.pem", destination.toString())); }); } public void createCA(Path caKey, Path config, Path destination) { } }
package de.fhg.iais.roberta.visitor.codegen; import java.util.ArrayList; import org.json.JSONObject; import de.fhg.iais.roberta.components.Configuration; import de.fhg.iais.roberta.components.ConfigurationComponent; import de.fhg.iais.roberta.inter.mode.action.IDriveDirection; import de.fhg.iais.roberta.inter.mode.action.ILanguage; import de.fhg.iais.roberta.inter.mode.action.ITurnDirection; import de.fhg.iais.roberta.mode.action.DriveDirection; import de.fhg.iais.roberta.mode.action.Language; import de.fhg.iais.roberta.mode.action.TurnDirection; import de.fhg.iais.roberta.syntax.MotorDuration; import de.fhg.iais.roberta.syntax.Phrase; import de.fhg.iais.roberta.syntax.SC; import de.fhg.iais.roberta.syntax.action.display.ClearDisplayAction; import de.fhg.iais.roberta.syntax.action.display.ShowTextAction; import de.fhg.iais.roberta.syntax.action.light.LightAction; import de.fhg.iais.roberta.syntax.action.light.LightStatusAction; import de.fhg.iais.roberta.syntax.action.motor.MotorGetPowerAction; import de.fhg.iais.roberta.syntax.action.motor.MotorOnAction; import de.fhg.iais.roberta.syntax.action.motor.MotorSetPowerAction; import de.fhg.iais.roberta.syntax.action.motor.MotorStopAction; import de.fhg.iais.roberta.syntax.action.motor.differential.CurveAction; import de.fhg.iais.roberta.syntax.action.motor.differential.DriveAction; import de.fhg.iais.roberta.syntax.action.motor.differential.MotorDriveStopAction; import de.fhg.iais.roberta.syntax.action.motor.differential.TurnAction; import de.fhg.iais.roberta.syntax.action.sound.PlayFileAction; import de.fhg.iais.roberta.syntax.action.sound.PlayNoteAction; import de.fhg.iais.roberta.syntax.action.sound.ToneAction; import de.fhg.iais.roberta.syntax.action.sound.VolumeAction; import de.fhg.iais.roberta.syntax.lang.expr.ColorConst; import de.fhg.iais.roberta.syntax.lang.stmt.AssertStmt; import de.fhg.iais.roberta.syntax.lang.stmt.DebugAction; import de.fhg.iais.roberta.syntax.sensor.generic.*; import de.fhg.iais.roberta.typecheck.NepoInfo; import de.fhg.iais.roberta.util.dbc.Assert; import de.fhg.iais.roberta.util.dbc.DbcException; import de.fhg.iais.roberta.visitor.C; import de.fhg.iais.roberta.visitor.hardware.INxtVisitor; import de.fhg.iais.roberta.visitor.lang.codegen.AbstractStackMachineVisitor; public class NxtStackMachineVisitor<V> extends AbstractStackMachineVisitor<V> implements INxtVisitor<V> { private NxtStackMachineVisitor(Configuration configuration, ArrayList<ArrayList<Phrase<Void>>> phrases, ILanguage language) { super(configuration); Assert.isTrue(!phrases.isEmpty()); } public static String generate(Configuration brickConfiguration, ArrayList<ArrayList<Phrase<Void>>> phrasesSet, ILanguage language) { Assert.isTrue(!phrasesSet.isEmpty()); Assert.notNull(brickConfiguration); NxtStackMachineVisitor<Void> astVisitor = new NxtStackMachineVisitor<>(brickConfiguration, phrasesSet, language); astVisitor.generateCodeFromPhrases(phrasesSet); JSONObject generatedCode = new JSONObject(); generatedCode.put(C.OPS, astVisitor.opArray).put(C.FUNCTION_DECLARATION, astVisitor.fctDecls); return generatedCode.toString(2); } @Override public V visitColorConst(ColorConst<V> colorConst) { String color = ""; switch ( colorConst.getHexValueAsString().toUpperCase() ) { case "#000000": color = "BLACK"; break; case "#0057A6": color = "BLUE"; break; case "#00642E": color = "GREEN"; break; case "#F7D117": color = "YELLOW"; break; case "#B30006": color = "RED"; break; case "#FFFFFF": color = "WHITE"; break; case "#532115": color = "BROWN"; break; case "#EE82EE": color = "VIOLET"; break; case "#800080": color = "PURPLE"; break; case "#00FF00": color = "LIME"; break; case "#FFA500": color = "ORANGE"; break; case "#FF00FF": color = "MAGENTA"; break; case "#DC143C": color = "CRIMSON"; case "#585858": color = "NONE"; break; default: colorConst.addInfo(NepoInfo.error("SIM_BLOCK_NOT_SUPPORTED")); throw new DbcException("Invalid color constant: " + colorConst.getHexValueAsString()); } JSONObject o = mk(C.EXPR).put(C.EXPR, C.COLOR_CONST).put(C.VALUE, color); return app(o); } @Override public V visitClearDisplayAction(ClearDisplayAction<V> clearDisplayAction) { JSONObject o = mk(C.CLEAR_DISPLAY_ACTION); return app(o); } @Override public V visitLightStatusAction(LightStatusAction<V> lightStatusAction) { JSONObject o = mk(C.STATUS_LIGHT_ACTION).put(C.NAME, "ev3").put(C.PORT, "internal"); return app(o); } @Override public V visitToneAction(ToneAction<V> toneAction) { toneAction.getFrequency().visit(this); toneAction.getDuration().visit(this); JSONObject o = mk(C.TONE_ACTION); return app(o); } @Override public V visitPlayNoteAction(PlayNoteAction<V> playNoteAction) { String freq = playNoteAction.getFrequency(); String duration = playNoteAction.getDuration(); app(mk(C.EXPR).put(C.EXPR, C.NUM_CONST).put(C.VALUE, freq)); app(mk(C.EXPR).put(C.EXPR, C.NUM_CONST).put(C.VALUE, duration)); JSONObject o = mk(C.TONE_ACTION); return app(o); } @Override public V visitPlayFileAction(PlayFileAction<V> playFileAction) { String image = playFileAction.getFileName().toString(); JSONObject o = mk(C.PLAY_FILE_ACTION).put(C.FILE, image).put(C.NAME, "ev3"); return app(o); } @Override public V visitVolumeAction(VolumeAction<V> volumeAction) { JSONObject o; if ( volumeAction.getMode() == VolumeAction.Mode.GET ) { o = mk(C.GET_VOLUME); } else { volumeAction.getVolume().visit(this); o = mk(C.SET_VOLUME_ACTION); } return app(o); } @Override public V visitMotorGetPowerAction(MotorGetPowerAction<V> motorGetPowerAction) { String port = motorGetPowerAction.getUserDefinedPort(); JSONObject o = mk(C.MOTOR_GET_POWER).put(C.PORT, port.toLowerCase()); return app(o); } @Override public V visitDriveAction(DriveAction<V> driveAction) { driveAction.getParam().getSpeed().visit(this); MotorDuration<V> duration = driveAction.getParam().getDuration(); appendDuration(duration); ConfigurationComponent leftMotor = this.configuration.getFirstMotor(SC.LEFT); IDriveDirection leftMotorRotationDirection = DriveDirection.get(leftMotor.getProperty(SC.MOTOR_REVERSE)); DriveDirection driveDirection = (DriveDirection) driveAction.getDirection(); if ( leftMotorRotationDirection != DriveDirection.FOREWARD ) { driveDirection = getDriveDirection(driveAction.getDirection() == DriveDirection.FOREWARD); } JSONObject o = mk(C.DRIVE_ACTION).put(C.DRIVE_DIRECTION, driveDirection).put(C.NAME, "ev3"); if ( duration != null ) { app(o); return app(mk(C.STOP_DRIVE).put(C.NAME, "ev3")); } else { return app(o); } } @Override public V visitTurnAction(TurnAction<V> turnAction) { turnAction.getParam().getSpeed().visit(this); MotorDuration<V> duration = turnAction.getParam().getDuration(); appendDuration(duration); ConfigurationComponent leftMotor = this.configuration.getFirstMotor(SC.LEFT); IDriveDirection leftMotorRotationDirection = DriveDirection.get(leftMotor.getProperty(SC.MOTOR_REVERSE)); ITurnDirection turnDirection = turnAction.getDirection(); if ( leftMotorRotationDirection != DriveDirection.FOREWARD ) { turnDirection = getTurnDirection(turnAction.getDirection() == TurnDirection.LEFT); } JSONObject o = mk(C.TURN_ACTION).put(C.TURN_DIRECTION, turnDirection.toString().toLowerCase()).put(C.NAME, "ev3"); if ( duration != null ) { app(o); return app(mk(C.STOP_DRIVE).put(C.NAME, "ev3")); } else { return app(o); } } @Override public V visitCurveAction(CurveAction<V> curveAction) { curveAction.getParamLeft().getSpeed().visit(this); curveAction.getParamRight().getSpeed().visit(this); MotorDuration<V> duration = curveAction.getParamLeft().getDuration(); appendDuration(duration); ConfigurationComponent leftMotor = this.configuration.getFirstMotor(SC.LEFT); IDriveDirection leftMotorRotationDirection = DriveDirection.get(leftMotor.getProperty(SC.MOTOR_REVERSE)); DriveDirection driveDirection = (DriveDirection) curveAction.getDirection(); if ( leftMotorRotationDirection != DriveDirection.FOREWARD ) { driveDirection = getDriveDirection(curveAction.getDirection() == DriveDirection.FOREWARD); } JSONObject o = mk(C.CURVE_ACTION).put(C.DRIVE_DIRECTION, driveDirection).put(C.NAME, "ev3"); if ( duration != null ) { app(o); return app(mk(C.STOP_DRIVE).put(C.NAME, "ev3")); } else { return app(o); } } @Override public V visitMotorDriveStopAction(MotorDriveStopAction<V> stopAction) { JSONObject o = mk(C.STOP_DRIVE).put(C.NAME, "ev3"); return app(o); } @Override public V visitMotorOnAction(MotorOnAction<V> motorOnAction) { boolean isDuration = motorOnAction.getParam().getDuration() != null; motorOnAction.getParam().getSpeed().visit(this); String port = motorOnAction.getUserDefinedPort(); JSONObject o = mk(C.MOTOR_ON_ACTION).put(C.PORT, port.toLowerCase()).put(C.NAME, port.toLowerCase()); if ( isDuration ) { String durationType = motorOnAction.getParam().getDuration().getType().toString().toLowerCase(); motorOnAction.getParam().getDuration().getValue().visit(this); o.put(C.MOTOR_DURATION, durationType); app(o); return app(mk(C.MOTOR_STOP).put(C.PORT, port.toLowerCase())); } else { app(mk(C.EXPR).put(C.EXPR, C.NUM_CONST).put(C.VALUE, 0)); return app(o); } } @Override public V visitMotorSetPowerAction(MotorSetPowerAction<V> motorSetPowerAction) { String port = motorSetPowerAction.getUserDefinedPort(); motorSetPowerAction.getPower().visit(this); JSONObject o = mk(C.MOTOR_SET_POWER).put(C.PORT, port.toLowerCase()); return app(o); } @Override public V visitMotorStopAction(MotorStopAction<V> motorStopAction) { String port = motorStopAction.getUserDefinedPort(); JSONObject o = mk(C.MOTOR_STOP).put(C.PORT, port.toLowerCase()); return app(o); } @Override public V visitShowTextAction(ShowTextAction<V> showTextAction) { showTextAction.getY().visit(this); showTextAction.getX().visit(this); showTextAction.getMsg().visit(this); JSONObject o = mk(C.SHOW_TEXT_ACTION).put(C.NAME, "ev3"); return app(o); } @Override public V visitLightAction(LightAction<V> lightAction) { String mode = lightAction.getMode().toString().toLowerCase(); String color = lightAction.getColor().toString().toLowerCase(); JSONObject o = mk(C.LIGHT_ACTION).put(C.MODE, mode).put(C.COLOR, color); return app(o); } @Override public V visitTouchSensor(TouchSensor<V> touchSensor) { JSONObject o = mk(C.GET_SAMPLE).put(C.GET_SAMPLE, C.TOUCH).put(C.NAME, "ev3"); return app(o); } @Override public V visitColorSensor(ColorSensor<V> colorSensor) { String mode = colorSensor.getMode(); JSONObject o = mk(C.GET_SAMPLE).put(C.GET_SAMPLE, C.COLOR).put(C.MODE, mode.toLowerCase()).put(C.NAME, "ev3"); return app(o); } @Override public V visitEncoderSensor(EncoderSensor<V> encoderSensor) { String mode = encoderSensor.getMode().toLowerCase(); String port = encoderSensor.getPort().toLowerCase(); JSONObject o; if ( mode.equals(C.RESET) ) { o = mk(C.ENCODER_SENSOR_RESET).put(C.PORT, port).put(C.NAME, "ev3"); } else { o = mk(C.GET_SAMPLE).put(C.GET_SAMPLE, C.ENCODER_SENSOR_SAMPLE).put(C.PORT, port).put(C.MODE, mode).put(C.NAME, "ev3"); } return app(o); } @Override public V visitTemperatureSensor(TemperatureSensor<V> temperatureSensor) { String mode = temperatureSensor.getMode(); JSONObject o = mk(C.GET_SAMPLE).put(C.GET_SAMPLE, C.TEMPERATURE).put(C.PORT, mode.toLowerCase()).put(C.NAME, "ev3"); return app(o); } @Override public V visitKeysSensor(KeysSensor<V> keysSensor) { String mode = keysSensor.getPort().toLowerCase(); JSONObject o = mk(C.GET_SAMPLE).put(C.GET_SAMPLE, C.BUTTONS).put(C.MODE, mode).put(C.NAME, "ev3"); return app(o); } @Override public V visitLightSensor(LightSensor<V> lightSensor) { String mode = lightSensor.getMode().toLowerCase(); String port = lightSensor.getPort().toLowerCase(); JSONObject o = mk(C.GET_SAMPLE).put(C.GET_SAMPLE, C.COLOR).put(C.MODE, mode).put(C.PORT, port).put(C.NAME, "ev3"); return app(o); } @Override public V visitTimerSensor(TimerSensor<V> timerSensor) { String port = timerSensor.getPort(); JSONObject o; if ( timerSensor.getMode().equals(SC.DEFAULT) || timerSensor.getMode().equals(SC.VALUE) ) { o = mk(C.GET_SAMPLE).put(C.GET_SAMPLE, C.TIMER).put(C.PORT, port).put(C.NAME, "ev3"); } else { o = mk(C.TIMER_SENSOR_RESET).put(C.PORT, port).put(C.NAME, "ev3"); } return app(o); } @Override public V visitPinTouchSensor(PinTouchSensor<V> sensorGetSample) { String port = sensorGetSample.getPort(); String mode = sensorGetSample.getMode(); JSONObject o = mk(C.GET_SAMPLE).put(C.GET_SAMPLE, C.PIN + port).put(C.MODE, mode.toLowerCase()).put(C.NAME, "ev3"); return app(o); } @Override public V visitSoundSensor(SoundSensor<V> soundSensor) { JSONObject o = mk(C.GET_SAMPLE).put(C.GET_SAMPLE, C.SOUND).put(C.MODE, C.VOLUME).put(C.NAME, "ev3"); return app(o); } @Override public V visitCompassSensor(CompassSensor<V> compassSensor) { String mode = compassSensor.getMode(); JSONObject o = mk(C.GET_SAMPLE).put(C.GET_SAMPLE, C.COMPASS).put(C.MODE, mode.toLowerCase()).put(C.NAME, "ev3"); return app(o); } @Override public V visitGyroSensor(GyroSensor<V> gyroSensor) { String mode = gyroSensor.getMode().toLowerCase(); String port = gyroSensor.getPort().toLowerCase(); JSONObject o; if ( mode.equals(C.RESET) ) { o = mk(C.GYRO_SENSOR_RESET).put(C.PORT, port).put(C.NAME, "ev3"); } else { o = mk(C.GET_SAMPLE).put(C.GET_SAMPLE, C.GYRO).put(C.MODE, mode).put(C.NAME, "ev3"); } return app(o); } @Override public V visitAccelerometer(AccelerometerSensor<V> accelerometerSensor) { return null; } @Override public V visitHumiditySensor(HumiditySensor<V> humiditySensor) { return null; } @Override public V visitInfraredSensor(InfraredSensor<V> infraredSensor) { return null; } @Override public V visitUltrasonicSensor(UltrasonicSensor<V> ultrasonicSensor) { String mode = ultrasonicSensor.getMode(); JSONObject o = mk(C.GET_SAMPLE).put(C.GET_SAMPLE, C.ULTRASONIC).put(C.MODE, mode.toLowerCase()).put(C.NAME, "ev3"); return app(o); } private String getLanguageString(ILanguage language) { switch ( (Language) language ) { case GERMAN: return "de-DE"; case ENGLISH: return "en-US"; case FRENCH: return "fr-FR"; case SPANISH: return "es-ES"; case ITALIAN: return "it-IT"; case DUTCH: return "nl-NL"; case POLISH: return "pl-PL"; case RUSSIAN: return "ru-RU"; case PORTUGUESE: return "pt-BR"; case JAPANESE: return "ja-JP"; case CHINESE: return "zh-CN"; default: return ""; } } @Override protected void appendDuration(MotorDuration<V> duration) { if ( duration != null ) { duration.getValue().visit(this); } else { app(mk(C.EXPR).put(C.EXPR, C.NUM_CONST).put(C.VALUE, 0)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import org.apache.commons.io.FileUtils; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer; import org.apache.solr.client.solrj.request.AbstractUpdateRequest.ACTION; import org.apache.solr.client.solrj.request.QueryRequest; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.core.SolrCore; import org.junit.AfterClass; import org.junit.BeforeClass; public class AnalysisAfterCoreReloadTest extends SolrTestCaseJ4 { private static String tmpSolrHome; int port = 0; static final String context = "/solr"; static final String collection = "collection1"; @BeforeClass public static void beforeClass() throws Exception { tmpSolrHome = createTempDir().toFile().getAbsolutePath(); FileUtils.copyDirectory(new File(TEST_HOME()), new File(tmpSolrHome).getAbsoluteFile()); initCore("solrconfig.xml", "schema.xml", new File(tmpSolrHome).getAbsolutePath()); } @AfterClass public static void AfterClass() throws Exception {} public void testStopwordsAfterCoreReload() throws Exception { SolrInputDocument doc = new SolrInputDocument(); doc.setField("id", "42"); doc.setField("teststop", "terma stopworda stopwordb stopwordc"); // default stopwords - stopworda and stopwordb UpdateRequest up = new UpdateRequest(); up.setAction(ACTION.COMMIT, true, true); up.add(doc); up.process(getSolrCore()); SolrQuery q = new SolrQuery(); QueryRequest r = new QueryRequest(q); q.setQuery("teststop:terma"); assertEquals(1, r.process(getSolrCore()).getResults().size()); q = new SolrQuery(); r = new QueryRequest(q); q.setQuery("teststop:stopworda"); assertEquals(0, r.process(getSolrCore()).getResults().size()); q = new SolrQuery(); r = new QueryRequest(q); q.setQuery("teststop:stopwordb"); assertEquals(0, r.process(getSolrCore()).getResults().size()); q = new SolrQuery(); r = new QueryRequest(q); q.setQuery("teststop:stopwordc"); assertEquals(1, r.process(getSolrCore()).getResults().size()); // overwrite stopwords file with stopword list ["stopwordc"] and reload the core overwriteStopwords("stopwordc\n"); h.getCoreContainer().reload(collection); up.process(getSolrCore()); q = new SolrQuery(); r = new QueryRequest(q); q.setQuery("teststop:terma"); assertEquals(1, r.process(getSolrCore()).getResults().size()); q = new SolrQuery(); r = new QueryRequest(q); q.setQuery("teststop:stopworda"); // stopworda is no longer a stopword assertEquals(1, r.process(getSolrCore()).getResults().size()); q = new SolrQuery(); r = new QueryRequest(q); q.setQuery("teststop:stopwordb"); // stopwordb is no longer a stopword assertEquals(1, r.process(getSolrCore()).getResults().size()); q = new SolrQuery(); r = new QueryRequest(q); q.setQuery("teststop:stopwordc"); // stopwordc should be a stopword assertEquals(0, r.process(getSolrCore()).getResults().size()); } private void overwriteStopwords(String stopwords) throws IOException { try (SolrCore core = h.getCoreContainer().getCore(collection)) { Path configPath = core.getResourceLoader().getConfigPath(); Files.move(configPath.resolve("stopwords.txt"), configPath.resolve("stopwords.txt.bak")); Files.write(configPath.resolve("stopwords.txt"), stopwords.getBytes(StandardCharsets.UTF_8)); } } @Override public void tearDown() throws Exception { Path configPath; try (SolrCore core = h.getCoreContainer().getCore(collection)) { configPath = core.getResourceLoader().getConfigPath(); } super.tearDown(); Path backupFile = configPath.resolve("stopwords.txt.bak"); if (Files.exists(backupFile)) { Files.move(backupFile, configPath.resolve("stopwords.txt"), REPLACE_EXISTING); } } protected SolrClient getSolrCore() { return new EmbeddedSolrServer(h.getCoreContainer(), collection); } }
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iotanalytics.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.iotanalytics.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * BatchPutMessageResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class BatchPutMessageResultJsonUnmarshaller implements Unmarshaller<BatchPutMessageResult, JsonUnmarshallerContext> { public BatchPutMessageResult unmarshall(JsonUnmarshallerContext context) throws Exception { BatchPutMessageResult batchPutMessageResult = new BatchPutMessageResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return batchPutMessageResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("batchPutMessageErrorEntries", targetDepth)) { context.nextToken(); batchPutMessageResult.setBatchPutMessageErrorEntries(new ListUnmarshaller<BatchPutMessageErrorEntry>( BatchPutMessageErrorEntryJsonUnmarshaller.getInstance()) .unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return batchPutMessageResult; } private static BatchPutMessageResultJsonUnmarshaller instance; public static BatchPutMessageResultJsonUnmarshaller getInstance() { if (instance == null) instance = new BatchPutMessageResultJsonUnmarshaller(); return instance; } }
package com.gradecak.alfresco.mvc.controller; import org.alfresco.service.cmr.repository.NodeRef; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; @ControllerAdvice(assignableTypes = TestController.class) public class TestControllerAdvice implements ResponseBodyAdvice<NodeRef> { @Override public NodeRef beforeBodyWrite(NodeRef body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { response.getHeaders().add("TEST_ADVICE_APPLIED", "true"); return new NodeRef("a://a/b"); } @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { return converterType.isAssignableFrom(MappingJackson2HttpMessageConverter.class); } }
package com.standards.libhikvision.activity.widget.slice; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.graphics.Typeface; import android.text.TextPaint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.ViewGroup; import com.standards.libhikvision.R; import com.standards.libhikvision.util.DisplayUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author CRAWLER */ public class ScalableTimebarView extends View { /** * Indicates how many pixels a tick corresponds to for 1 second at the current scale criterion */ private float pixelsPerSecond = 0; /** * Timebar Action Listeners */ private OnBarMoveListener mOnBarMoveListener; private OnBarScaledListener mOnBarScaledListener; /** * Screen width and height in pixel */ private int screenWidth, screenHeight; /** * Paint to draw timebar body, ticks and RecordBar */ Paint timebarPaint = new Paint(); /** * Textpaint to draw time text corresponding to large ticks */ TextPaint keyTickTextPaint = new TextPaint(); /** * Margin between large tick and time text corresponding to it in dp */ private final int TICK_TEXT_TO_TICK_MARGIN_IN_DP = 2; /** * Whole height of the ScalableTimebarView (including timebar, recordbar, time text, margins, and so on) in dp */ private final int VIEW_HEIGHT_IN_DP = 80; /** * Height of recordbar in dp */ private final int COLORED_RECORDBAR_HEIGHT_IN_DP = 40; /** * Time text size corresponding to large ticks(key ticks) in sp */ private final int KEY_TICK_TEXT_SIZE_IN_SP = 18; /** * Height of Triangle */ private final int BIG_TICK_HEIGHT_IN_DP = 10; /** * Line Length of Triangle */ private final int IND_TRIANGLE_BOTTOM_LINE_IN_DP = 12; /** * Line Length of Triangle */ private final int IND_TRIANGLE_HEIGHT_IN_DP = 8; /** * Line Length of Triangle */ private final int IND_LINE_WIDTH_IN_DP = 1; /** * Height of small tick in dp */ private final int SMALL_TICK_HEIGHT_IN_DP = 6; /** * Half the width of large tick in dp */ private final int BIG_TICK_HALF_WIDTH_IN_DP = 2; /** * Half the width of small tick in dp */ private final int SMALL_TICK_HALF_WIDTH_IN_DP = 1; /** * Margin between recordbar and tick text in dp */ private final int COLORED_RECORDBAR_TO_TICK_TEXT_MARGIN_IN_DP = 5; /** * The white cursor bitmap width to show */ private final int MIDDLE_CURSOR_BITMAP_SCALED_WIDTH_IN_DP = 13; /** * Convert various dimensions from dp/sp to px */ private int BIG_TICK_HALF_WIDTH = DisplayUtils.dp2px(getContext(), BIG_TICK_HALF_WIDTH_IN_DP); private int BIG_TICK_HEIGHT = DisplayUtils.dp2px(getContext(), BIG_TICK_HEIGHT_IN_DP); private int IND_TRIANGLE_BOTTOM_LINE_LENGTH = DisplayUtils.dp2px(getContext(), IND_TRIANGLE_BOTTOM_LINE_IN_DP); private int IND_TRIANGLE_HEIGHT = DisplayUtils.dp2px(getContext(), IND_TRIANGLE_HEIGHT_IN_DP); private int IND_LINE_WIDTH = DisplayUtils.dp2px(getContext(), IND_LINE_WIDTH_IN_DP); private int SMALL_TICK_HALF_WIDTH = DisplayUtils.dp2px(getContext(), SMALL_TICK_HALF_WIDTH_IN_DP); private int SMALL_TICK_HEIGHT = DisplayUtils.dp2px(getContext(), SMALL_TICK_HEIGHT_IN_DP); private int KEY_TICK_TEXT_SIZE = DisplayUtils.dp2px(getContext(), KEY_TICK_TEXT_SIZE_IN_SP); private int TICK_TEXT_TO_TICK_MARGIN = DisplayUtils.dp2px(getContext(), TICK_TEXT_TO_TICK_MARGIN_IN_DP); private int VIEW_HEIGHT = DisplayUtils.dp2px(getContext(), VIEW_HEIGHT_IN_DP); private int COLORED_RECORDBAR_TO_TICK_TEXT_MARGIN = DisplayUtils.dp2px(getContext(), COLORED_RECORDBAR_TO_TICK_TEXT_MARGIN_IN_DP); private int COLORED_RECORDBAR_HEIGHT = DisplayUtils.dp2px(getContext(), COLORED_RECORDBAR_HEIGHT_IN_DP); /** * color */ private int UN_DISPLAY_LINE_COLOR; private int DISPLAY_LINE_COLOR; private int INDICATOR_TRIANGLE_COLOR; private int INDICATOR_LINE_COLOR; private int TICK_LINE_COLOR; private int TICK_TEXT_COLOR; private int OUT_OF_RANGE_COLOR; private int RECOR_COLOR; /** * Set whether middle white cursor visible. */ private boolean middleCursorVisible = true; /** * Map to cache 5 scale criterions */ private Map<Integer, TimebarTickCriterion> timebarTickCriterionMap = new HashMap<>(); /** * Timebar scale criterion count */ private int timebarTickCriterionCount = 5; /** * Indicating which scale criterions the view is using to show ticks now , corresponding to keys of "timebarTickCriterionMap" */ private int currentTimebarTickCriterionIndex; /** * Storage of record data. Each time segment means one visible segment to be drawn colored on recordbar.<br> * This is the original recordbar data set by developer. */ private List<RecordDataExistTimeSegment> recordDataExistTimeClipsList = new ArrayList<>(); /** * Data in recordDataExistTimeClipsList are divided into different groups and cached in this map.<br> * Same-day segments are grouped together in the same group.<br> * Keys of this map is milliseconds corresponding to 00:00 on the date. */ private Map<Long, List<RecordDataExistTimeSegment>> recordDataExistTimeClipsListMap = new HashMap<>(); /** * Detector to handle scale gesture */ private ScaleGestureDetector scaleGestureDetector; /** * Indicate whether width of this view has been initialized */ private boolean notInited = true; /** * Current time the white cursor indicating in millisecond */ private long currentTimeInMillisecond; /** * Time corresponding to the most left tick (earlist time) in whole ScalableTimebarView (maybe outside the screen display range) */ private long mostLeftTimeInMillisecond; /** * Time corresponding to the most right tick (latest time) in whole ScalableTimebarView (maybe outside the screen display range) */ private long mostRightTimeInMillisecond; /** * Time corresponding to the most left tick (latest time) visible on screen now */ private long screenLeftTimeInMillisecond; /** * Time corresponding to the most right tick (latest time) visible on screen now */ private long screenRightTimeInMillisecond; /** * Flag indicating whether onMeasure() is called because of scale operation (scale operation can be performed by scale gesture or clicking on zoom buttons) */ private boolean justScaledByPressingButton = false; /** * Seconds in one day */ public final static int SECONDS_PER_DAY = 24 * 60 * 60; /** * The length of the entire timebar view, excluding the extra half-screen empty width at both ends. */ private long WHOLE_TIMEBAR_TOTAL_SECONDS; public ScalableTimebarView(Context context) { super(context); init(null); } public ScalableTimebarView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } public ScalableTimebarView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public List<RecordDataExistTimeSegment> getRecordDataExistTimeClipsList() { return recordDataExistTimeClipsList; } public void setRecordDataExistTimeClipsList(List<RecordDataExistTimeSegment> recordDataExistTimeClipsList) { this.recordDataExistTimeClipsList = recordDataExistTimeClipsList; arrangeRecordDataExistTimeClipsIntoMap(recordDataExistTimeClipsList); } /** * Get most left (earlist) time in this whole view (including the invisible part outside the screen) */ public long getMostLeftTimeInMillisecond() { return mostLeftTimeInMillisecond; } /** * Get most right (latest) time in this whole view (including the invisible part outside the screen) */ public long getMostRightTimeInMillisecond() { return mostRightTimeInMillisecond; } public long getScreenLeftTimeInMillisecond() { screenLeftTimeInMillisecond = (long) (getCurrentTimeInMillisecond() - (long) ((float) screenWidth * 1000f / 2f / pixelsPerSecond)); return screenLeftTimeInMillisecond; } public long getScreenRightTimeInMillisecond() { screenRightTimeInMillisecond = (long) (getCurrentTimeInMillisecond() + (long) (screenWidth * 1000f / 2f / pixelsPerSecond)); return screenRightTimeInMillisecond; } private void arrangeRecordDataExistTimeClipsIntoMap(List<RecordDataExistTimeSegment> clipsList) { recordDataExistTimeClipsListMap = new HashMap<>(); if (clipsList != null) { for (RecordDataExistTimeSegment clipItem : clipsList) { for (Long dateZeroOClockItem : clipItem.getCoverDateZeroOClockList()) { List<RecordDataExistTimeSegment> list = null; if ((list = recordDataExistTimeClipsListMap.get(dateZeroOClockItem)) == null) { list = new ArrayList<>(); recordDataExistTimeClipsListMap.put(dateZeroOClockItem, list); } list.add(clipItem); } } } invalidate(); } /** * Initializes start time, end time and current cursor time of ScalableTimebarView. * This method is called only when the view is initialized. * If you just need to move the current time cursor position, call setCurrentTimeInMillisecond() instead. * <p> * * @param mostLeftTime Time corresponding to the most left tick (earlist time) in whole ScalableTimebarView (maybe outside the screen display range) * @param mostRightTime Time corresponding to the most right tick (latest time) in whole ScalableTimebarView (maybe outside the screen display range) * @param currentTime Current time the white cursor indicating in millisecond */ public void initTimebarLengthAndPosition(long mostLeftTime, long mostRightTime, long currentTime) { this.mostLeftTimeInMillisecond = mostLeftTime; this.mostRightTimeInMillisecond = mostRightTime; this.currentTimeInMillisecond = currentTime; WHOLE_TIMEBAR_TOTAL_SECONDS = (mostRightTime - mostLeftTime) / 1000; initTimebarTickCriterionMap(); } public int getCurrentTimebarTickCriterionIndex() { return currentTimebarTickCriterionIndex; } public void setCurrentTimebarTickCriterionIndex(int currentTimebarTickCriterionIndex) { this.currentTimebarTickCriterionIndex = currentTimebarTickCriterionIndex; } private void init(AttributeSet attrs) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ScalableTimebarView); BIG_TICK_HALF_WIDTH = (int) a.getDimension(R.styleable.ScalableTimebarView_bigTickWidth, BIG_TICK_HALF_WIDTH); BIG_TICK_HEIGHT = (int) a.getDimension(R.styleable.ScalableTimebarView_bigTickHeight, BIG_TICK_HEIGHT); IND_TRIANGLE_BOTTOM_LINE_LENGTH = (int) a.getDimension(R.styleable.ScalableTimebarView_bottomTriangleWidth, IND_TRIANGLE_BOTTOM_LINE_LENGTH); IND_TRIANGLE_HEIGHT = (int) a.getDimension(R.styleable.ScalableTimebarView_bottomTriangleHeight, IND_TRIANGLE_HEIGHT); IND_LINE_WIDTH = (int) a.getDimension(R.styleable.ScalableTimebarView_lineWidth, IND_LINE_WIDTH); SMALL_TICK_HALF_WIDTH = (int) a.getDimension(R.styleable.ScalableTimebarView_smallTickWidth, SMALL_TICK_HALF_WIDTH); SMALL_TICK_HEIGHT = (int) a.getDimension(R.styleable.ScalableTimebarView_smallTickHeight, SMALL_TICK_HEIGHT); KEY_TICK_TEXT_SIZE = (int) a.getDimension(R.styleable.ScalableTimebarView_tickTextSize, KEY_TICK_TEXT_SIZE); TICK_TEXT_TO_TICK_MARGIN = (int) a.getDimension(R.styleable.ScalableTimebarView_bigTickToTickText, TICK_TEXT_TO_TICK_MARGIN); COLORED_RECORDBAR_HEIGHT = (int) a.getDimension(R.styleable.ScalableTimebarView_colorBarHeight, COLORED_RECORDBAR_HEIGHT); VIEW_HEIGHT = BIG_TICK_HEIGHT + SMALL_TICK_HEIGHT + KEY_TICK_TEXT_SIZE + TICK_TEXT_TO_TICK_MARGIN + COLORED_RECORDBAR_HEIGHT + IND_TRIANGLE_HEIGHT; UN_DISPLAY_LINE_COLOR = a.getColor(R.styleable.ScalableTimebarView_unDisplayLineColor, getResources().getColor(R.color.colorLightBlue)); DISPLAY_LINE_COLOR = a.getColor(R.styleable.ScalableTimebarView_unDisplayLineColor, getResources().getColor(R.color.colorMainBlue)); INDICATOR_TRIANGLE_COLOR = a.getColor(R.styleable.ScalableTimebarView_indicateTriangleColor, getResources().getColor(R.color.colorMainBlue)); INDICATOR_LINE_COLOR = a.getColor(R.styleable.ScalableTimebarView_indicateLineColor, getResources().getColor(R.color.color_gray)); TICK_LINE_COLOR = a.getColor(R.styleable.ScalableTimebarView_tickLineColor, getResources().getColor(R.color.color_gray)); TICK_TEXT_COLOR = a.getColor(R.styleable.ScalableTimebarView_tickTextColor, getResources().getColor(R.color.colorMainText)); OUT_OF_RANGE_COLOR = a.getColor(R.styleable.ScalableTimebarView_outOfRangeColor, getResources().getColor(R.color.color_gray)); RECOR_COLOR = a.getColor(R.styleable.ScalableTimebarView_recordColor, getResources().getColor(R.color.colorRecordGreen)); a.recycle(); screenWidth = DisplayUtils.getScreenWidthPixels(getContext()); screenHeight = DisplayUtils.getScreenHeightPixels(getContext()); // By default we use scale criterion[3] to show ticks. // By default, the current cursor is set to 3 hours before System.currentTimeMillis(), // and the mostRightTimeInMillisecond of the timebar is set System.currentTimeMillis() currentTimeInMillisecond = System.currentTimeMillis() - 3 * 3600 * 1000; mostRightTimeInMillisecond = currentTimeInMillisecond + 3 * 3600 * 1000; // By default the whole view width (including the parts outside the screen) is set to 7 days length mostLeftTimeInMillisecond = mostRightTimeInMillisecond - 2 * 24 * 3600 * 1000; WHOLE_TIMEBAR_TOTAL_SECONDS = (mostRightTimeInMillisecond - mostLeftTimeInMillisecond) / 1000; pixelsPerSecond = (float) (getWidth() - screenWidth) / (float) WHOLE_TIMEBAR_TOTAL_SECONDS; initTimebarTickCriterionMap(); setCurrentTimebarTickCriterionIndex(3); keyTickTextPaint.setTextSize(KEY_TICK_TEXT_SIZE); keyTickTextPaint.setTypeface(Typeface.DEFAULT); keyTickTextPaint.setColor(TICK_TEXT_COLOR); ScaleGestureDetector.OnScaleGestureListener scaleGestureListener = new ScaleGestureDetector.OnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { scaleTimebarByFactor(detector.getScaleFactor(), false); return true; } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { justScaledByPressingButton = true; } }; scaleGestureDetector = new ScaleGestureDetector(getContext(), scaleGestureListener); } /** * Scale the view by factor * * @param scaleFactor scale factor * @param scaleByClickButton true:scale view by click zoom buttons * false:scale vie by scale gesture */ public void scaleTimebarByFactor(float scaleFactor, boolean scaleByClickButton) { int newWidth = (int) ((getWidth() - screenWidth) * scaleFactor); if (newWidth > timebarTickCriterionMap.get(0).getViewLength()) { setCurrentTimebarTickCriterionIndex(0); newWidth = timebarTickCriterionMap.get(0).getViewLength(); } else if (newWidth < timebarTickCriterionMap.get(0).getViewLength() && newWidth >= getAverageWidthForTwoCriterion(0, 1)) { setCurrentTimebarTickCriterionIndex(0); } else if (newWidth < getAverageWidthForTwoCriterion(0, 1) && newWidth >= getAverageWidthForTwoCriterion(1, 2)) { setCurrentTimebarTickCriterionIndex(1); } else if (newWidth < getAverageWidthForTwoCriterion(1, 2) && newWidth >= getAverageWidthForTwoCriterion(2, 3)) { setCurrentTimebarTickCriterionIndex(2); } else if (newWidth < getAverageWidthForTwoCriterion(2, 3) && newWidth >= timebarTickCriterionMap.get(3).getViewLength()) { setCurrentTimebarTickCriterionIndex(3); } else if (newWidth < getAverageWidthForTwoCriterion(3, 4) && newWidth >= timebarTickCriterionMap.get(4).getViewLength()) { setCurrentTimebarTickCriterionIndex(4); } else if (newWidth < timebarTickCriterionMap.get(4).getViewLength()) { setCurrentTimebarTickCriterionIndex(4); newWidth = timebarTickCriterionMap.get(4).getViewLength(); } if (scaleByClickButton) { justScaledByPressingButton = true; } ViewGroup.LayoutParams params = getLayoutParams(); params.width = newWidth; setLayoutParams(params); } private float getAverageWidthForTwoCriterion(int criterion1Index, int criterion2Index) { int width1 = timebarTickCriterionMap.get(criterion1Index).getViewLength(); int width2 = timebarTickCriterionMap.get(criterion2Index).getViewLength(); return (width1 + width2) / 2; } /** * <p> * According to the level of scaling, preset 5 scale criterions to show ticks on timebar, respectively, as follows: * <p> * [<b>Glossary</b>]<br/> * LoTSW: The Length of Time can be displayed throughout the Screen Width <br/> * TILT: The Time Interval between two Large Ticks(Also called key ticks) <br/> * TIST: The Time Interval between two Small Ticks <br/> * <pre> * (0)LoTSW:10 minutes TILT:1 minutes TIST:6 seconds * (1)LoTSW:1 hours TILT:10 minutes TIST:1 minutes * (2)LoTSW:6 hours TILT:1 hours TIST:5 minutes * (3)LoTSW:36 hours TILT:6 hours TIST:30 minutes * (4)LoTSW:6 days TILT:1 days TIST:2 hours * </pre> */ private void initTimebarTickCriterionMap() { TimebarTickCriterion t0 = new TimebarTickCriterion(); t0.setTotalSecondsInOneScreen(10 * 60); t0.setKeyTickInSecond(1 * 60); t0.setMinTickInSecond(6); t0.setDataPattern("HH:mm"); t0.setViewLength((int) ((float) screenWidth * WHOLE_TIMEBAR_TOTAL_SECONDS / (float) t0.getTotalSecondsInOneScreen())); timebarTickCriterionMap.put(0, t0); TimebarTickCriterion t1 = new TimebarTickCriterion(); t1.setTotalSecondsInOneScreen(60 * 60); t1.setKeyTickInSecond(10 * 60); t1.setMinTickInSecond(60); t1.setDataPattern("HH:mm"); t1.setViewLength((int) ((float) screenWidth * WHOLE_TIMEBAR_TOTAL_SECONDS / (float) t1.getTotalSecondsInOneScreen())); timebarTickCriterionMap.put(1, t1); TimebarTickCriterion t2 = new TimebarTickCriterion(); t2.setTotalSecondsInOneScreen(6 * 60 * 60); t2.setKeyTickInSecond(60 * 60); t2.setMinTickInSecond(5 * 60); t2.setDataPattern("HH:mm"); t2.setViewLength((int) ((float) screenWidth * WHOLE_TIMEBAR_TOTAL_SECONDS / (float) t2.getTotalSecondsInOneScreen())); timebarTickCriterionMap.put(2, t2); TimebarTickCriterion t3 = new TimebarTickCriterion(); t3.setTotalSecondsInOneScreen(24 * 60 * 60); t3.setKeyTickInSecond(6 * 60 * 60); t3.setMinTickInSecond(30 * 60); t3.setDataPattern("HH:mm"); t3.setViewLength((int) ((float) screenWidth * WHOLE_TIMEBAR_TOTAL_SECONDS / (float) t3.getTotalSecondsInOneScreen())); timebarTickCriterionMap.put(3, t3); TimebarTickCriterion t4 = new TimebarTickCriterion(); t4.setTotalSecondsInOneScreen(6 * 24 * 60 * 60); t4.setKeyTickInSecond(24 * 60 * 60); t4.setMinTickInSecond(2 * 60 * 60); t4.setDataPattern("MM.dd"); // t4.dataPattern = "MM.dd HH:mm:ss"; t4.setViewLength((int) ((float) screenWidth * WHOLE_TIMEBAR_TOTAL_SECONDS / (float) t4.getTotalSecondsInOneScreen())); timebarTickCriterionMap.put(4, t4); timebarTickCriterionCount = timebarTickCriterionMap.size(); } /** * Reset view width to default value */ private void resetToStandardWidth() { setCurrentTimebarTickCriterionIndex(3); ViewGroup.LayoutParams params = getLayoutParams(); params.width = timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getViewLength(); setLayoutParams(params); } /** * Get current time indicating by white cursor bitmap */ public long getCurrentTimeInMillisecond() { return currentTimeInMillisecond; } /** * Set current time cursor to specific time point. * If you are playing a video and use this ScalableTimebarView to indicate play progress, * then you should call this method every minute to update the showing current time. * * @param currentTimeInMillisecond current time you want to indicate by cursor */ public void setCurrentTimeInMillisecond(long currentTimeInMillisecond) { this.currentTimeInMillisecond = currentTimeInMillisecond; invalidate(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureWidth(widthMeasureSpec), VIEW_HEIGHT); if (justScaledByPressingButton && mOnBarScaledListener != null) { justScaledByPressingButton = false; mOnBarScaledListener.onBarScaleFinish(getScreenLeftTimeInMillisecond(), getScreenRightTimeInMillisecond(), currentTimeInMillisecond); } } /** * Measure width of this view. * Left end and right end are both reserved for half the width of the screen * * @param widthMeasureSpec widthMeasureSpec * @return measured width */ private int measureWidth(int widthMeasureSpec) { int measureMode = MeasureSpec.getMode(widthMeasureSpec); int measureSize = MeasureSpec.getSize(widthMeasureSpec); int result = getSuggestedMinimumWidth(); switch (measureMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: result = measureSize + screenWidth; pixelsPerSecond = measureSize / (float) WHOLE_TIMEBAR_TOTAL_SECONDS; if (mOnBarScaledListener != null) { mOnBarScaledListener.onBarScaled(getScreenLeftTimeInMillisecond(), getScreenRightTimeInMillisecond(), currentTimeInMillisecond); } break; default: break; } return result; } /** * Convert time in millisecond to display string. * The display string style is controlled by current scale criterion. * * @param value time in millisecond need to convert * @return display string */ private String getTimeStringFromLong(long value) { SimpleDateFormat timeFormat = new SimpleDateFormat(timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getDataPattern()); return timeFormat.format(value); } /** * Set if you want middle cursor bitmap to be visible * * @param middleCursorVisible true:visible * false:invisible */ public void setMiddleCursorVisible(boolean middleCursorVisible) { this.middleCursorVisible = middleCursorVisible; invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (notInited) { notInited = false; resetToStandardWidth(); return; } pixelsPerSecond = (float) (getWidth() - screenWidth) / (float) WHOLE_TIMEBAR_TOTAL_SECONDS; //Get the number of milliseconds between the phone's local time zone and UTC Calendar cal = Calendar.getInstance(); int zoneOffsetInSeconds = cal.get(Calendar.ZONE_OFFSET) / 1000; long forStartUTC = (long) (currentTimeInMillisecond / 1000 - screenWidth / pixelsPerSecond / 2 - timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond()); long forEndUTC = (long) (currentTimeInMillisecond / 1000 + screenWidth / pixelsPerSecond / 2 + timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond()); long forStartLocalTimezone = forStartUTC + zoneOffsetInSeconds; long forEndLocalTimezone = forEndUTC + zoneOffsetInSeconds; //Look for the first tick to show on screen long firstTickToSeeInSecondUTC = -1; for (long i = forStartLocalTimezone; i <= forEndLocalTimezone; i++) { if (i % timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond() == 0) { firstTickToSeeInSecondUTC = i - zoneOffsetInSeconds; break; } } /** * Draw timebar body , large ticks, small ticks, and time text corresponding to large ticks */ int totalTickToDrawInOneScreen = (int) (screenWidth / pixelsPerSecond / timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond()) + 2; float keytextY = getHeight() - IND_TRIANGLE_HEIGHT - COLORED_RECORDBAR_HEIGHT - BIG_TICK_HEIGHT - TICK_TEXT_TO_TICK_MARGIN; for (int i = -20; i <= totalTickToDrawInOneScreen + 10; i++) { long drawTickTimeInSecondUTC = firstTickToSeeInSecondUTC + i * timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond(); long drawTickTimeInSecondLocalTimezone = drawTickTimeInSecondUTC + zoneOffsetInSeconds; //关键刻度 if (drawTickTimeInSecondLocalTimezone % timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getKeyTickInSecond() == 0) { //draw large ticks timebarPaint.setColor(TICK_LINE_COLOR); timebarPaint.setStyle(Paint.Style.FILL); float startX = pixelsPerSecond * (drawTickTimeInSecondUTC - mostLeftTimeInMillisecond / 1000) + screenWidth / 2f; RectF largeTickRect = new RectF(startX - BIG_TICK_HALF_WIDTH / 2, getHeight() - BIG_TICK_HEIGHT - IND_TRIANGLE_HEIGHT - COLORED_RECORDBAR_HEIGHT, (startX + BIG_TICK_HALF_WIDTH / 2), getHeight() - COLORED_RECORDBAR_HEIGHT - IND_TRIANGLE_HEIGHT); canvas.drawRect(largeTickRect, timebarPaint); //draw time text String keytext = getTimeStringFromLong(drawTickTimeInSecondUTC * 1000); float keyTextWidth = keyTickTextPaint.measureText(keytext); float keytextX = startX - keyTextWidth / 2; canvas.drawText(keytext, keytextX, keytextY, keyTickTextPaint); } else if (drawTickTimeInSecondLocalTimezone % timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond() == 0) { //draw small ticks timebarPaint.setColor(TICK_LINE_COLOR); timebarPaint.setStyle(Paint.Style.FILL); float startX = pixelsPerSecond * (drawTickTimeInSecondUTC - mostLeftTimeInMillisecond / 1000) + screenWidth / 2f; RectF smallTickRect = new RectF(startX - SMALL_TICK_HALF_WIDTH / 2, getHeight() - SMALL_TICK_HEIGHT - IND_TRIANGLE_HEIGHT - COLORED_RECORDBAR_HEIGHT, (startX + SMALL_TICK_HALF_WIDTH / 2), getHeight() - IND_TRIANGLE_HEIGHT - COLORED_RECORDBAR_HEIGHT); canvas.drawRect(smallTickRect, timebarPaint); } } /** * Draw recordbar */ //Draw grey background long startDrawTimeInSeconds = firstTickToSeeInSecondUTC + (-20) * timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond();//灰色背景从哪个时间点开始,单位是毫秒 float startX = pixelsPerSecond * (startDrawTimeInSeconds - mostLeftTimeInMillisecond / 1000) + screenWidth / 2f; float endX = (startX + screenWidth + timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond() * 40 * pixelsPerSecond); float startY = getHeight() - IND_TRIANGLE_HEIGHT - COLORED_RECORDBAR_HEIGHT; float endY = getHeight() - IND_TRIANGLE_HEIGHT; RectF cloudRecordTimeClipsBarBackgroundRectF = new RectF(startX, startY, endX, endY); timebarPaint.setColor(DISPLAY_LINE_COLOR); timebarPaint.setStyle(Paint.Style.FILL); canvas.drawRect(cloudRecordTimeClipsBarBackgroundRectF, timebarPaint); //绘制不可选取灰色区域 drawRange(canvas, 0, screenWidth / 2, startY, endY, OUT_OF_RANGE_COLOR); // 绘制不可选取灰色区域 drawRange(canvas, getWidth() - screenWidth / 2, getWidth(), startY, endY, OUT_OF_RANGE_COLOR); //浅蓝色未播放区域 float unPlayStartX = (currentTimeInMillisecond - mostLeftTimeInMillisecond) / 1000 * pixelsPerSecond + screenWidth / 2; drawRange(canvas, unPlayStartX, getWidth() - screenWidth / 2, startY, endY, UN_DISPLAY_LINE_COLOR); if (recordDataExistTimeClipsList != null && recordDataExistTimeClipsList.size() > 0) { //绘制特殊时间片 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat zeroTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String startDrawTimeDateString = dateFormat.format(startDrawTimeInSeconds * 1000); String zeroTimeString = startDrawTimeDateString + " 00:00:00"; long screenLastSecondToSee = (long) (startDrawTimeInSeconds + screenWidth / pixelsPerSecond + 30 * timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond()) * 1000L; Date startDate; try { //Find the date of most left (earlist) time on screen. Then get the list in cloudRecordExistTimeClipsListMap whose key is 00:00 of this date. //Get the first item in the list, using it as start condition to search which record segment should be the first to draw on recordbar. startDate = zeroTimeFormat.parse(zeroTimeString); List<RecordDataExistTimeSegment> startList = recordDataExistTimeClipsListMap.get(startDate.getTime()); if (startList == null) { int afterFindDays = 1; long findTimeInMilliseconds = startDate.getTime(); long newFindStartMilliseconds = findTimeInMilliseconds; while (startList == null && newFindStartMilliseconds < screenLastSecondToSee) { newFindStartMilliseconds = findTimeInMilliseconds + (long) SECONDS_PER_DAY * 1000L * (long) afterFindDays; startList = recordDataExistTimeClipsListMap.get(newFindStartMilliseconds); afterFindDays++; } } if (startList != null && startList.size() > 0) { int thisDateFirstClipStartIndex = recordDataExistTimeClipsList.indexOf(startList.get(0)); //The first record segment should be drawn is found. Now let's start to draw colorful record segments! long endDrawTimeInSeconds = (long) (startDrawTimeInSeconds + screenWidth / pixelsPerSecond + timebarTickCriterionMap.get(currentTimebarTickCriterionIndex).getMinTickInSecond() * 30); timebarPaint.setColor(RECOR_COLOR); timebarPaint.setStyle(Paint.Style.FILL); for (int i = thisDateFirstClipStartIndex; i < recordDataExistTimeClipsList.size(); i++) { float leftX = pixelsPerSecond * (recordDataExistTimeClipsList.get(i).getStartTimeInMillisecond() - mostLeftTimeInMillisecond) / 1000 + screenWidth / 2f; float rightX = pixelsPerSecond * (recordDataExistTimeClipsList.get(i).getEndTimeInMillisecond() - mostLeftTimeInMillisecond) / 1000 + screenWidth / 2f; RectF rectF = new RectF(leftX, startY, rightX, endY); canvas.drawRect(rectF, timebarPaint); if (recordDataExistTimeClipsList.get(i).getEndTimeInMillisecond() >= endDrawTimeInSeconds * 1000) { break; } } } } catch (ParseException e) { e.printStackTrace(); } } /** * Draw white cursor bitmap indicating current time in the middle of screen */ if (middleCursorVisible) { timebarPaint.setColor(INDICATOR_TRIANGLE_COLOR); timebarPaint.setStyle(Paint.Style.FILL); Path path = new Path(); path.moveTo((currentTimeInMillisecond / 1000L - mostLeftTimeInMillisecond / 1000L) * pixelsPerSecond + screenWidth / 2f - IND_TRIANGLE_BOTTOM_LINE_LENGTH / 2, getHeight());// 此点为多边形的起点 path.lineTo((currentTimeInMillisecond / 1000L - mostLeftTimeInMillisecond / 1000L) * pixelsPerSecond + screenWidth / 2f + IND_TRIANGLE_BOTTOM_LINE_LENGTH / 2, getHeight()); path.lineTo((currentTimeInMillisecond / 1000L - mostLeftTimeInMillisecond / 1000L) * pixelsPerSecond + screenWidth / 2f, getHeight() - IND_TRIANGLE_HEIGHT); path.close(); // 使这些点构成封闭的多边形 canvas.drawPath(path, timebarPaint); timebarPaint.setStrokeWidth(IND_LINE_WIDTH); timebarPaint.setColor(INDICATOR_LINE_COLOR); canvas.drawLine((currentTimeInMillisecond / 1000L - mostLeftTimeInMillisecond / 1000L) * pixelsPerSecond + screenWidth / 2f, getHeight() - IND_TRIANGLE_HEIGHT, (currentTimeInMillisecond / 1000L - mostLeftTimeInMillisecond / 1000L) * pixelsPerSecond + screenWidth / 2f, getHeight() - IND_TRIANGLE_HEIGHT - COLORED_RECORDBAR_HEIGHT, timebarPaint); } /** * According to the currentTimeInMillisecond variable, layout the view in appropriate location */ layout((int) (0 - (currentTimeInMillisecond - mostLeftTimeInMillisecond) / 1000 * pixelsPerSecond), getTop(), getWidth() - (int) ((currentTimeInMillisecond - mostLeftTimeInMillisecond) / 1000 * pixelsPerSecond), getTop() + getHeight()); } private void drawRange(Canvas canvas, float startX, float endX, float startY, float endY, int color) { RectF cloudRecordTimeClipsBarBackgroundRectF = new RectF(startX, startY, endX, endY); timebarPaint.setColor(color); timebarPaint.setStyle(Paint.Style.FILL); canvas.drawRect(cloudRecordTimeClipsBarBackgroundRectF, timebarPaint); } /** * Coordinates when draging timebar */ float lastX, lastY; /** * Current operation on this view */ private int mode = NONE; private static final int NONE = 0; private static final int DRAG = 1; private static final int ZOOM = 2; @Override public boolean onTouchEvent(MotionEvent event) { scaleGestureDetector.onTouchEvent(event); if (scaleGestureDetector.isInProgress()) { return true; } switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: mode = DRAG; lastX = event.getRawX(); lastY = event.getRawY(); break; case MotionEvent.ACTION_POINTER_DOWN: mode = ZOOM; break; case MotionEvent.ACTION_MOVE: if (mode == ZOOM) { } else if (mode == DRAG) { int dx = (int) (event.getRawX() - lastX); int dy = (int) (event.getRawY() - lastY); if (dx == 0) { return true; } int top = getTop(); int left = getLeft() + dx; int right = left + getWidth(); if (left >= 0) { left = 0; right = getWidth(); } if (right < screenWidth) { right = screenWidth; left = right - getWidth(); } layout(left, top, right, top + getHeight()); invalidate(); lastX = event.getRawX(); lastY = event.getRawY(); //pixels to move int deltaX = (0 - left); int timeBarLength = getWidth() - screenWidth; currentTimeInMillisecond = mostLeftTimeInMillisecond + deltaX * WHOLE_TIMEBAR_TOTAL_SECONDS * 1000 / timeBarLength; if (mOnBarMoveListener != null) { mOnBarMoveListener.onBarMove(getScreenLeftTimeInMillisecond(), getScreenRightTimeInMillisecond(), currentTimeInMillisecond); } } break; case MotionEvent.ACTION_UP: if (mode == DRAG) { int deltaX_up = (0 - getLeft()); int timeBarLength_up = getWidth() - screenWidth; currentTimeInMillisecond = mostLeftTimeInMillisecond + deltaX_up * WHOLE_TIMEBAR_TOTAL_SECONDS * 1000 / timeBarLength_up; if (mOnBarMoveListener != null) { mOnBarMoveListener.OnBarMoveFinish(getScreenLeftTimeInMillisecond(), getScreenRightTimeInMillisecond(), currentTimeInMillisecond); } } mode = NONE; break; default: break; } return true; } /** * Listener while moving and finish move */ public interface OnBarMoveListener { /** * Callback when the timebar is being moved horizontal(slide) * * @param screenLeftTime most left time on screen (ony visible part of this view) * @param screenRightTime most right time on screen (only visible part of this view) * @param currentTime current time */ void onBarMove(long screenLeftTime, long screenRightTime, long currentTime); /** * Callback when the timebar finish moving * * @param screenLeftTime most left time on screen (only visible part of this view) * @param screenRightTime most right time on screen (only visible part of this view) * @param currentTime current time */ void OnBarMoveFinish(long screenLeftTime, long screenRightTime, long currentTime); } public void setOnBarMoveListener(OnBarMoveListener onBarMoveListener) { mOnBarMoveListener = onBarMoveListener; } /** * Listener while scale and finish scale */ public interface OnBarScaledListener { /** * Called when timebar is being scaled * * @param screenLeftTime most left time on screen (only visible part of this view) * @param screenRightTime most right time on screen (only visible part of this view) * @param currentTime current time */ void onBarScaled(long screenLeftTime, long screenRightTime, long currentTime); /** * Called when finish scaling * * @param screenLeftTime most left time on screen (only visible part of this view) * @param screenRightTime most right time on screen (only visible part of this view) * @param currentTime current time */ void onBarScaleFinish(long screenLeftTime, long screenRightTime, long currentTime); } public void setOnBarScaledListener(OnBarScaledListener onBarScaledListener) { mOnBarScaledListener = onBarScaledListener; } }
/* * Copyright 2018 Crown Copyright * * 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 uk.gov.gchq.gaffer.graph.hook; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import org.apache.commons.collections.CollectionUtils; import uk.gov.gchq.gaffer.data.elementdefinition.view.View; import uk.gov.gchq.gaffer.data.elementdefinition.view.ViewElementDefinition; import uk.gov.gchq.gaffer.operation.Operation; import uk.gov.gchq.gaffer.operation.OperationChain; import uk.gov.gchq.gaffer.operation.graph.OperationView; import uk.gov.gchq.gaffer.store.Context; import uk.gov.gchq.gaffer.user.User; import java.util.Map.Entry; import java.util.Set; /** * This is a hook to update all operation views in a chain before it is executed. * This hook can be configured to add additional view configurations such as extra filters * and it can also be used to remove element groups out of a view. * This hook will have no effect with operations that do not correctly implement {@link OperationView} * therefore <b>THIS HOOK SHOULD NOT BE USED TO ENFORCE ROLE BASED FILTERING OF ELEMENTS</b>. * Instead please make use of the visibility property ({@link uk.gov.gchq.gaffer.store.schema.Schema#visibilityProperty}). * <p> * All fields are Optional: * <ul> * <li>withOpAuth = Apply this hook to Users with <b>any</b> of these operation authorisations</li> * <li>withoutOpAuth = Apply this hook to Users <b>without any</b> of these operation authorisations, overrides withOpAuth</li> * <li>withDataAuth = Apply this hook to Users with <b>any</b> of these data authorisations</li> * <li>withoutDataAuth = Apply this hook to Users <b>without any</b> of these data authorisations, overrides withDataAuth</li> * <li>whiteListElementGroups = When this hook is applied, only allow View Element Groups from this list, overrides viewToMerge</li> * <li>blackListElementGroups = When this hook is applied, remove all View Element Groups from this list, overrides whiteListElementGroups and viewToMerge</li> * <li>viewToMerge = the view to be merged into the current view.</li> * </ul> * If the user matches the opAuth or dataAuth criteria the following is applied: * <ul> * <li>First the viewToMerge is merged into the user provided operation view.</li> * <li>Then the white list of element groups is applied.</li> * <li>Then the black list of element groups is applied.</li> * </ul> * * @see GraphHook * @see uk.gov.gchq.gaffer.store.schema.Schema#visibilityProperty */ public class UpdateViewHook implements GraphHook { public static final boolean ADD_EXTRA_GROUPS_DEFAULT = false; private Set<String> withOpAuth; private Set<String> withoutOpAuth; private Set<String> withDataAuth; private Set<String> withoutDataAuth; private Set<String> whiteListElementGroups; private Set<String> blackListElementGroups; private byte[] viewToMerge; private boolean addExtraGroups = ADD_EXTRA_GROUPS_DEFAULT; @Override public void preExecute(final OperationChain<?> opChain, final Context context) { if (applyToUser(context.getUser())) { updateView(opChain); } } private void updateView(final OperationChain<?> opChain) { for (final Operation operation : opChain.flatten()) { if (operation instanceof OperationView) { final OperationView operationView = (OperationView) operation; final View.Builder viewBuilder = mergeView(operationView, getViewToMerge()); if ((null != whiteListElementGroups && !whiteListElementGroups.isEmpty()) || (null != blackListElementGroups && !blackListElementGroups.isEmpty())) { viewBuilder.removeEntities(this::removeElementGroups); viewBuilder.removeEdges(this::removeElementGroups); } if (!addExtraGroups && null != operationView.getView()) { final Set<String> entityGroups = operationView.getView().getEntityGroups(); viewBuilder.removeEntities(grp -> null == entityGroups || !entityGroups.contains(grp.getKey())); final Set<String> edgeGroups = operationView.getView().getEdgeGroups(); viewBuilder.removeEdges(grp -> null == edgeGroups || !edgeGroups.contains(grp.getKey())); } viewBuilder.expandGlobalDefinitions(); operationView.setView(viewBuilder.build()); } } } protected final View.Builder mergeView(final OperationView operationView, final View viewToMerge) { View.Builder viewBuilder = new View.Builder() .merge(operationView.getView()); if (null != viewToMerge) { viewBuilder.merge(viewToMerge.clone()); } return viewBuilder; } protected final boolean removeElementGroups(final Entry<String, ViewElementDefinition> entry) { boolean remove; if (null != whiteListElementGroups) { remove = !whiteListElementGroups.contains(entry.getKey()); } else { remove = false; } if (!remove) { if (null != blackListElementGroups) { remove = blackListElementGroups.contains(entry.getKey()); } } return remove; } protected final boolean applyToUser(final User user) { return userContainsWithDataAuth(user) && userContainsWithOpAuth(user) && userNotContainsWithoutDataAuth(user) && userNotContainsWithoutOpAuth(user); } private boolean userNotContainsWithoutOpAuth(final User user) { return !validateAuths(user.getOpAuths(), this.withoutOpAuth, false); } private boolean userNotContainsWithoutDataAuth(final User user) { return !validateAuths(user.getDataAuths(), this.withoutDataAuth, false); } private boolean userContainsWithOpAuth(final User user) { return validateAuths(user.getOpAuths(), this.withOpAuth, true); } private boolean userContainsWithDataAuth(final User user) { return validateAuths(user.getDataAuths(), this.withDataAuth, true); } protected final boolean validateAuths(final Set<String> userAuths, final Set<String> validAuth, final boolean ifValidAuthIsNull) { boolean rtn = ifValidAuthIsNull; if (null != validAuth) { if (null == userAuths) { rtn = validAuth.isEmpty(); } else { rtn = CollectionUtils.containsAny(userAuths, validAuth); } } return rtn; } @Override public <T> T postExecute(final T result, final OperationChain<?> opChain, final Context context) { return result; } @Override public <T> T onFailure(final T result, final OperationChain<?> opChain, final Context context, final Exception e) { return result; } @JsonGetter("withOpAuth") public Set<String> getWithOpAuth() { return withOpAuth; } @JsonSetter("withOpAuth") public UpdateViewHook setWithOpAuth(final Set<String> withOpAuth) { this.withOpAuth = withOpAuth; return this; } @JsonGetter("withoutOpAuth") public Set<String> getWithoutOpAuth() { return withoutOpAuth; } @JsonSetter("withoutOpAuth") public UpdateViewHook setWithoutOpAuth(final Set<String> withoutOpAuth) { this.withoutOpAuth = withoutOpAuth; return this; } @JsonGetter("withDataAuth") public Set<String> getWithDataAuth() { return withDataAuth; } @JsonSetter("withDataAuth") public UpdateViewHook setWithDataAuth(final Set<String> withDataAuth) { this.withDataAuth = withDataAuth; return this; } @JsonGetter("withoutDataAuth") public Set<String> getWithoutDataAuth() { return withoutDataAuth; } @JsonSetter("withoutDataAuth") public UpdateViewHook setWithoutDataAuth(final Set<String> withoutDataAuth) { this.withoutDataAuth = withoutDataAuth; return this; } @JsonGetter("whiteListElementGroups") public Set<String> getWhiteListElementGroups() { return whiteListElementGroups; } @JsonSetter("whiteListElementGroups") public UpdateViewHook setWhiteListElementGroups(final Set<String> whiteListElementGroups) { this.whiteListElementGroups = whiteListElementGroups; return this; } @JsonGetter("blackListElementGroups") public Set<String> getBlackListElementGroups() { return blackListElementGroups; } @JsonSetter("blackListElementGroups") public UpdateViewHook setBlackListElementGroups(final Set<String> blackListElementGroups) { this.blackListElementGroups = blackListElementGroups; return this; } @JsonSetter("viewToMerge") public UpdateViewHook setViewToMerge(final View viewToMerge) { this.viewToMerge = null != viewToMerge ? viewToMerge.toCompactJson() : null; return this; } @JsonGetter("viewToMerge") public View getViewToMerge() { return null != viewToMerge ? View.fromJson(viewToMerge) : null; } public boolean isAddExtraGroups() { return addExtraGroups; } public UpdateViewHook setAddExtraGroups(final boolean addExtraGroups) { this.addExtraGroups = addExtraGroups; return this; } public static class Builder { private Set<String> withOpAuth; private Set<String> withoutOpAuth; private Set<String> withDataAuth; private Set<String> withoutDataAuth; private Set<String> whiteListElementGroups; private Set<String> blackListElementGroups; private View viewToMerge; private boolean addExtraGroups; public Builder withOpAuth(final Set<String> withOpAuth) { this.withOpAuth = withOpAuth; return this; } public Builder withoutOpAuth(final Set<String> withoutOpAuth) { this.withoutOpAuth = withoutOpAuth; return this; } public Builder withDataAuth(final Set<String> withDataAuths) { this.withDataAuth = withDataAuths; return this; } public Builder withoutDataAuth(final Set<String> withoutDataAuth) { this.withoutDataAuth = withoutDataAuth; return this; } public Builder whiteListElementGroups(final Set<String> whiteListElementGroups) { this.whiteListElementGroups = whiteListElementGroups; return this; } public Builder blackListElementGroups(final Set<String> blackListElementGroups) { this.blackListElementGroups = blackListElementGroups; return this; } public Builder setViewToMerge(final View viewToMerge) { this.viewToMerge = viewToMerge; return this; } public Builder addExtraGroups(final boolean addExtraGroups) { this.addExtraGroups = addExtraGroups; return this; } public UpdateViewHook build() { return new UpdateViewHook() .setWithOpAuth(withOpAuth) .setWithoutOpAuth(withoutOpAuth) .setWithDataAuth(withDataAuth) .setWithoutDataAuth(withoutDataAuth) .setWhiteListElementGroups(whiteListElementGroups) .setBlackListElementGroups(blackListElementGroups) .setViewToMerge(viewToMerge) .setAddExtraGroups(addExtraGroups); } } }
/* * Copyright (C) 2017 优客服-多渠道客服系统 * Modifications copyright (C) 2018 Chatopera Inc, <https://www.chatopera.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.chatopera.cc.webim.web.handler.apps.setting; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import com.chatopera.cc.util.Menu; import com.chatopera.cc.webim.service.acd.ServiceQuene; import com.chatopera.cc.webim.service.cache.CacheHelper; import com.chatopera.cc.webim.service.repository.AdTypeRepository; import com.chatopera.cc.webim.service.repository.SessionConfigRepository; import com.chatopera.cc.webim.service.repository.TagRepository; import com.chatopera.cc.webim.service.repository.TemplateRepository; import com.chatopera.cc.webim.web.model.AdType; import com.chatopera.cc.webim.web.model.SysDic; import com.chatopera.cc.webim.web.model.Tag; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.chatopera.cc.core.UKDataContext; import com.chatopera.cc.util.UKTools; import com.chatopera.cc.webim.service.repository.BlackListRepository; import com.chatopera.cc.webim.web.handler.Handler; import com.chatopera.cc.webim.web.model.BlackEntity; import com.chatopera.cc.webim.web.model.SessionConfig; import com.chatopera.cc.webim.web.model.UKeFuDic; @Controller @RequestMapping("/setting") public class IMAgentController extends Handler{ @Autowired private SessionConfigRepository sessionConfigRes ; @Autowired private TagRepository tagRes ; @Autowired private BlackListRepository blackListRes; @Autowired private AdTypeRepository adTypeRes; @Autowired private TemplateRepository templateRes ; @Value("${web.upload-path}") private String path; @RequestMapping("/agent/index") @Menu(type = "setting" , subtype = "sessionconfig" , admin= false) public ModelAndView index(ModelMap map , HttpServletRequest request) { SessionConfig sessionConfig = sessionConfigRes.findByOrgi(super.getOrgi(request)) ; if(sessionConfig == null){ sessionConfig = new SessionConfig() ; } map.put("sessionConfig", sessionConfig) ; List<SysDic> dicList = UKeFuDic.getInstance().getDic(UKDataContext.UKEFU_SYSTEM_DIC) ; SysDic inputDic = null , outputDic = null ; for(SysDic dic : dicList){ if(dic.getCode().equals(UKDataContext.UKEFU_SYSTEM_AI_INPUT)){ inputDic = dic ; } if(dic.getCode().equals(UKDataContext.UKEFU_SYSTEM_AI_OUTPUT)){ outputDic = dic ; } } if(inputDic!=null){ map.addAttribute("innputtemlet", templateRes.findByTemplettypeAndOrgi(inputDic.getId(), super.getOrgi(request))) ; } if(outputDic!=null){ map.addAttribute("outputtemlet", templateRes.findByTemplettypeAndOrgi(outputDic.getId(), super.getOrgi(request))) ; } return request(super.createAppsTempletResponse("/apps/setting/agent/index")); } @RequestMapping("/agent/sessionconfig/save") @Menu(type = "setting" , subtype = "sessionconfig" , admin= false) public ModelAndView sessionconfig(ModelMap map , HttpServletRequest request , @Valid SessionConfig sessionConfig) { SessionConfig tempSessionConfig = sessionConfigRes.findByOrgi(super.getOrgi(request)) ; if(tempSessionConfig == null){ tempSessionConfig = sessionConfig; tempSessionConfig.setCreater(super.getUser(request).getId()); }else{ UKTools.copyProperties(sessionConfig, tempSessionConfig); } tempSessionConfig.setOrgi(super.getOrgi(request)); sessionConfigRes.save(tempSessionConfig) ; CacheHelper.getSystemCacheBean().put(UKDataContext.SYSTEM_CACHE_SESSION_CONFIG+"_"+super.getOrgi(request),tempSessionConfig, super.getOrgi(request)) ; CacheHelper.getSystemCacheBean().delete(UKDataContext.SYSTEM_CACHE_SESSION_CONFIG_LIST , UKDataContext.SYSTEM_ORGI) ; ServiceQuene.initSessionConfigList() ; map.put("sessionConfig", tempSessionConfig) ; return request(super.createRequestPageTempletResponse("redirect:/setting/agent/index.html")); } @RequestMapping("/blacklist") @Menu(type = "setting" , subtype = "blacklist" , admin= false) public ModelAndView blacklist(ModelMap map , HttpServletRequest request) { map.put("blackList", blackListRes.findByOrgi(super.getOrgi(request), new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC, "endtime"))) ; map.put("tagTypeList", UKeFuDic.getInstance().getDic("com.dic.tag.type")) ; return request(super.createAppsTempletResponse("/apps/setting/agent/blacklist")); } @RequestMapping("/blacklist/delete") @Menu(type = "setting" , subtype = "tag" , admin= false) public ModelAndView blacklistdelete(ModelMap map , HttpServletRequest request , @Valid String id) { if(!StringUtils.isBlank(id)){ BlackEntity tempBlackEntity = blackListRes.findByIdAndOrgi(id, super.getOrgi(request)) ; if(tempBlackEntity!=null){ blackListRes.delete(tempBlackEntity); CacheHelper.getSystemCacheBean().delete(tempBlackEntity.getUserid(), UKDataContext.SYSTEM_ORGI) ; } } return request(super.createRequestPageTempletResponse("redirect:/setting/blacklist.html")); } @RequestMapping("/tag") @Menu(type = "setting" , subtype = "tag" , admin= false) public ModelAndView tag(ModelMap map , HttpServletRequest request , @Valid String code) { SysDic tagType = null ; List<SysDic> tagList = UKeFuDic.getInstance().getDic("com.dic.tag.type") ; if(tagList.size() > 0){ if(!StringUtils.isBlank(code)){ for(SysDic dic : tagList){ if(code.equals(dic.getCode())){ tagType = dic ; } } }else{ tagType = tagList.get(0) ; } map.put("tagType", tagType) ; } if(tagType!=null){ map.put("tagList", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , tagType.getCode() , new PageRequest(super.getP(request), super.getPs(request)))) ; } map.put("tagTypeList", tagList) ; return request(super.createAppsTempletResponse("/apps/setting/agent/tag")); } @RequestMapping("/tag/add") @Menu(type = "setting" , subtype = "tag" , admin= false) public ModelAndView tagadd(ModelMap map , HttpServletRequest request , @Valid String tagtype) { map.addAttribute("tagtype", tagtype) ; return request(super.createRequestPageTempletResponse("/apps/setting/agent/tagadd")); } @RequestMapping("/tag/edit") @Menu(type = "setting" , subtype = "tag" , admin= false) public ModelAndView tagedit(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String tagtype) { map.put("tag", tagRes.findOne(id)) ; map.addAttribute("tagtype", tagtype) ; return request(super.createRequestPageTempletResponse("/apps/setting/agent/tagedit")); } @RequestMapping("/tag/update") @Menu(type = "setting" , subtype = "tag" , admin= false) public ModelAndView tagupdate(ModelMap map , HttpServletRequest request , @Valid Tag tag , @Valid String tagtype) { Tag temptag = tagRes.findByOrgiAndTag(super.getOrgi(request), tag.getTag()) ; if(temptag == null || tag.getId().equals(temptag.getId())){ tag.setOrgi(super.getOrgi(request)); tag.setCreater(super.getUser(request).getId()); tagRes.save(tag) ; } return request(super.createRequestPageTempletResponse("redirect:/setting/tag.html?code="+tagtype)); } @RequestMapping("/tag/save") @Menu(type = "setting" , subtype = "tag" , admin= false) public ModelAndView tagsave(ModelMap map , HttpServletRequest request , @Valid Tag tag , @Valid String tagtype) { if(tagRes.findByOrgiAndTag(super.getOrgi(request), tag.getTag()) == null){ tag.setOrgi(super.getOrgi(request)); tag.setCreater(super.getUser(request).getId()); tagRes.save(tag) ; } return request(super.createRequestPageTempletResponse("redirect:/setting/tag.html?code="+tagtype)); } @RequestMapping("/tag/delete") @Menu(type = "setting" , subtype = "tag" , admin= false) public ModelAndView tagdelete(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String tagtype) { tagRes.delete(id); return request(super.createRequestPageTempletResponse("redirect:/setting/tag.html?code="+tagtype)); } @RequestMapping("/acd") @Menu(type = "setting" , subtype = "acd" , admin= false) public ModelAndView acd(ModelMap map , HttpServletRequest request) { map.put("tagTypeList", UKeFuDic.getInstance().getDic("com.dic.tag.type")) ; return request(super.createAppsTempletResponse("/apps/setting/agent/acd")); } @RequestMapping("/adv") @Menu(type = "setting" , subtype = "adv" , admin= false) public ModelAndView adv(ModelMap map , HttpServletRequest request , @Valid String adpos) { SysDic advType = null ; List<SysDic> tagList = UKeFuDic.getInstance().getDic("com.dic.adv.type") ; if(tagList.size() > 0){ if(!StringUtils.isBlank(adpos)){ for(SysDic dic : tagList){ if(adpos.equals(dic.getId())){ advType = dic ; } } }else{ advType = tagList.get(0) ; } map.put("advType", advType) ; } if(advType!=null){ map.put("adTypeList", adTypeRes.findByAdposAndOrgi(advType.getId() , super.getOrgi(request))) ; } map.put("tagTypeList", UKeFuDic.getInstance().getDic("com.dic.tag.type")) ; map.put("advTypeList", UKeFuDic.getInstance().getDic("com.dic.adv.type")) ; return request(super.createAppsTempletResponse("/apps/setting/agent/adv")); } @RequestMapping("/adv/add") @Menu(type = "setting" , subtype = "adv" , admin= false) public ModelAndView advadd(ModelMap map , HttpServletRequest request , @Valid String adpos) { map.addAttribute("adpos", adpos) ; return request(super.createRequestPageTempletResponse("/apps/setting/agent/adadd")); } @RequestMapping("/adv/save") @Menu(type = "setting" , subtype = "adv" , admin= false) public ModelAndView advsave(ModelMap map , HttpServletRequest request , @Valid AdType adv , @Valid String advtype , @RequestParam(value = "imgfile", required = false) MultipartFile imgfile) throws IOException { adv.setOrgi(super.getOrgi(request)); adv.setCreater(super.getUser(request).getId()); if(!StringUtils.isBlank(adv.getContent())){ adv.setContent(adv.getContent().replaceAll("\"", "'")); } adv.setCreatetime(new Date()); if(imgfile!=null && imgfile.getSize() > 0){ File adDir = new File(path , "adv"); if(!adDir.exists()){ adDir.mkdirs() ; } String fileName = "adv/"+UKTools.getUUID()+imgfile.getOriginalFilename().substring(imgfile.getOriginalFilename().lastIndexOf(".")) ; FileCopyUtils.copy(imgfile.getBytes(), new File(path , fileName)); adv.setImgurl("/res/image.html?id="+java.net.URLEncoder.encode(fileName , "UTF-8")); } adTypeRes.save(adv) ; UKTools.initAdv(super.getOrgi(request)); return request(super.createRequestPageTempletResponse("redirect:/setting/adv.html?adpos="+adv.getAdpos())); } @RequestMapping("/adv/edit") @Menu(type = "setting" , subtype = "adv" , admin= false) public ModelAndView advedit(ModelMap map , HttpServletRequest request , @Valid String adpos, @Valid String id) { map.addAttribute("adpos", adpos) ; map.put("ad", adTypeRes.findByIdAndOrgi(id , super.getOrgi(request))) ; return request(super.createRequestPageTempletResponse("/apps/setting/agent/adedit")); } @RequestMapping("/adv/update") @Menu(type = "setting" , subtype = "adv" , admin= false) public ModelAndView advupdate(ModelMap map , HttpServletRequest request , @Valid AdType ad, @Valid String adpos, @RequestParam(value = "imgfile", required = false) MultipartFile imgfile) throws IOException { AdType tempad = adTypeRes.findByIdAndOrgi(ad.getId(),super.getOrgi(request)) ; if(tempad != null){ ad.setOrgi(super.getOrgi(request)); ad.setCreater(tempad.getCreater()); ad.setCreatetime(tempad.getCreatetime()); if(!StringUtils.isBlank(ad.getContent())){ ad.setContent(ad.getContent().replaceAll("\"", "'")); } if(imgfile!=null && imgfile.getSize() > 0){ File adDir = new File(path , "adv"); if(!adDir.exists()){ adDir.mkdirs() ; } String fileName = "adv/"+UKTools.getUUID()+imgfile.getOriginalFilename().substring(imgfile.getOriginalFilename().lastIndexOf(".")) ; FileCopyUtils.copy(imgfile.getBytes(), new File(path , fileName)); ad.setImgurl("/res/image.html?id="+java.net.URLEncoder.encode(fileName , "UTF-8")); }else{ ad.setImgurl(tempad.getImgurl()); } adTypeRes.save(ad) ; UKTools.initAdv(super.getOrgi(request)); } return request(super.createRequestPageTempletResponse("redirect:/setting/adv.html?adpos="+adpos)); } @RequestMapping("/adv/delete") @Menu(type = "setting" , subtype = "adv" , admin= false) public ModelAndView advdelete(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String adpos) { adTypeRes.delete(id); UKTools.initAdv(super.getOrgi(request)); return request(super.createRequestPageTempletResponse("redirect:/setting/adv.html?adpos="+adpos)); } }
package org.appspot.apprtc; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import org.webrtc.IceCandidate; import org.webrtc.SessionDescription; import org.appspot.apprtc.janus.JanusCommon; import org.appspot.apprtc.janus.JanusCommon.JanusConnectionParameters; import org.appspot.apprtc.janus.JanusCommon.JanusServerState; import org.appspot.apprtc.janus.JanusRTCEvents2; import org.appspot.apprtc.janus.JanusTransaction2; import org.appspot.apprtc.janus.JanusHandle; import static org.appspot.apprtc.janus.JanusUtils.randomString; import static org.appspot.apprtc.janus.JanusUtils.jsonPut; import static org.appspot.apprtc.janus.JanusUtils.convertSdpToJson; import static org.appspot.apprtc.janus.JanusUtils.convertJsonToCandidate; import org.appspot.apprtc.WebSocketChannelClient.WebSocketChannelEvents; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.math.BigInteger; import java.util.concurrent.ConcurrentHashMap; public class VideoRoomClient implements WebSocketChannelEvents { private static final String TAG = "VideoRoomClient"; private final Handler handler; private WebSocketChannelClient wsClient; private JanusRTCEvents2 events; private JanusServerState state; private JanusConnectionParameters connectionParameters; private ConcurrentHashMap<String, JanusTransaction2> transactionMap = new ConcurrentHashMap<>(); private ConcurrentHashMap<BigInteger, JanusHandle> handleMap = new ConcurrentHashMap<>(); private ConcurrentHashMap<BigInteger, BigInteger> feedMap = new ConcurrentHashMap<>(); private BigInteger sessionId, privateId; public VideoRoomClient(JanusRTCEvents2 events) { this.events = events; this.sessionId = BigInteger.ZERO; this.privateId = BigInteger.ZERO; this.state = JanusServerState.NEW; final HandlerThread handlerThread = new HandlerThread(TAG); handlerThread.start(); handler = new Handler(handlerThread.getLooper()); } // ---------------------------------------------------------------------------- // Basic functions by activity calling // ---------------------------------------------------------------------------- public void connectToServer(JanusConnectionParameters connectionParameters) { this.connectionParameters = connectionParameters; handler.post(new Runnable() { @Override public void run() { init(); } }); } public void disconnectFromServer() { handler.post(new Runnable() { @Override public void run() { disconnect(); handler.getLooper().quit(); } }); } public void publisherCreateOffer(final BigInteger handleId, final SessionDescription sdp) { handler.post(new Runnable() { @Override public void run() { createOffer(handleId, sdp); } }); } public void subscriberCreateAnswer(final BigInteger handleId, final SessionDescription sdp){ handler.post(new Runnable() { @Override public void run() { createAnswer(handleId, sdp); } }); } public void trickleCandidate(final BigInteger handleId, final IceCandidate iceCandidate) { handler.post(new Runnable() { @Override public void run() { trickle(handleId, iceCandidate); } }); } public void trickleCandidateComplete(final BigInteger handleId) { handler.post(new Runnable() { @Override public void run() { trickleComplete(handleId); } }); } // ---------------------------------------------------------------------------- // Internal transaction functions // ---------------------------------------------------------------------------- private void init() { wsClient = new WebSocketChannelClient(handler, this); wsClient.connect(connectionParameters.wsServerUrl, connectionParameters.subProtocols); } private void create() { checkIfCalledOnValidThread(); if(state != JanusServerState.NEW && state != JanusServerState.CLOSED) { Log.w(TAG, "create() in a error state -- " + state); return; } JanusTransaction2 JanusTransaction2 = new JanusTransaction2(); JanusTransaction2.transactionId = randomString(12); JanusTransaction2.events = new JanusTransaction2.TransactionEvents() { @Override public void success(BigInteger id) { sessionId = id; setState(JanusServerState.CONNECTED); handler.post(fireKeepAlive); attach(BigInteger.ZERO, connectionParameters.userDisplay); } @Override public void error(String reason, String code) { //fixme: retry Log.e(TAG,"Transaction error: " + code + " " + reason); reportError(reason); } }; transactionMap.put(JanusTransaction2.transactionId, JanusTransaction2); JSONObject json = new JSONObject(); jsonPut(json, "janus", "create"); jsonPut(json, "transaction", JanusTransaction2.transactionId); wsClient.send(json.toString()); } private void keepAlive() { checkIfCalledOnValidThread(); if(state != JanusServerState.CONNECTED) { Log.w(TAG, "keepalive() in a error state -- " + state); return; } JSONObject json = new JSONObject(); jsonPut(json, "janus", "keepalive"); jsonPut(json, "session_id", sessionId); jsonPut(json, "transaction", randomString(12)); wsClient.send(json.toString()); } private Runnable fireKeepAlive = new Runnable() { @Override public void run() { keepAlive(); handler.postDelayed(fireKeepAlive, JanusCommon.delayMillis); } }; private void attach(final BigInteger feedId, final String display){ checkIfCalledOnValidThread(); if(state != JanusServerState.CONNECTED) { Log.w(TAG, "attach() in a error state -- " + state); return; } JanusTransaction2 JanusTransaction2 = new JanusTransaction2(); JanusTransaction2.transactionId = randomString(12); JanusTransaction2.events = new JanusTransaction2.TransactionEvents() { @Override public void success(BigInteger id) { JanusHandle janusHandle = new JanusHandle(); janusHandle.handleId = id; if(feedId == BigInteger.ZERO) janusHandle.feedId = id; // attach publisher else janusHandle.feedId = feedId; // attach subscriber janusHandle.display = display; handleMap.put(janusHandle.handleId, janusHandle); feedMap.put(janusHandle.feedId, janusHandle.handleId); join(janusHandle.handleId, feedId); } @Override public void error(String reason, String code) { //fixme: retry Log.e(TAG,"Transaction error: " + code + " " + reason); reportError(reason); } }; transactionMap.put(JanusTransaction2.transactionId, JanusTransaction2); JSONObject json = new JSONObject(); jsonPut(json, "janus", "attach"); jsonPut(json, "session_id", sessionId); jsonPut(json, "plugin", "janus.plugin.videoroom"); jsonPut(json, "transaction", JanusTransaction2.transactionId); wsClient.send(json.toString()); } private void join(BigInteger handleId, BigInteger feedId) { checkIfCalledOnValidThread(); if(state != JanusServerState.CONNECTED) { Log.w(TAG, "join() in a error state -- " + state); return; } JanusTransaction2 JanusTransaction2 = new JanusTransaction2(); JanusTransaction2.transactionId = randomString(12); JanusTransaction2.events = new JanusTransaction2.TransactionEvents() { // publisher joined @Override public void success(BigInteger id) { if (handleMap.get(id) == null) { Log.e(TAG, "onWebSocketMessage: missing handle " + id); } else { events.onPublisherJoined(id); } } // subscriber joined @Override public void success(BigInteger id, JSONObject jsep) { if (handleMap.get(id) == null) { Log.e(TAG, "onWebSocketMessage: missing handle " + id); } else { events.onRemoteJsep(handleId, jsep); } } @Override public void error(String reason, String code) { //fixme: retry Log.e(TAG,"Transaction error: " + code + " " + reason); reportError(reason); } }; transactionMap.put(JanusTransaction2.transactionId, JanusTransaction2); JSONObject json = new JSONObject(); JSONObject jsonBody = new JSONObject(); jsonPut(jsonBody, "request", "join"); jsonPut(jsonBody, "room", connectionParameters.roomId); if(feedId == BigInteger.ZERO) { jsonPut(jsonBody, "ptype", "publisher"); jsonPut(jsonBody, "display", connectionParameters.userDisplay); } else { jsonPut(jsonBody, "ptype", "subscriber"); jsonPut(jsonBody, "feed", feedId); jsonPut(jsonBody, "private_id", privateId); } jsonPut(json, "janus", "message"); jsonPut(json, "body", jsonBody); jsonPut(json, "session_id", sessionId); jsonPut(json, "handle_id", handleId); jsonPut(json, "transaction", JanusTransaction2.transactionId); wsClient.send(json.toString()); } private void createOffer(BigInteger handleId, SessionDescription sdp) { checkIfCalledOnValidThread(); if(state != JanusServerState.CONNECTED) { Log.w(TAG, "join() in a error state -- " + state); return; } JanusTransaction2 JanusTransaction2 = new JanusTransaction2(); JanusTransaction2.transactionId = randomString(12); JanusTransaction2.events = new JanusTransaction2.TransactionEvents() { @Override public void success(BigInteger id, JSONObject jsep) { if (handleMap.get(id) == null) { Log.e(TAG, "offerConfigured: missing handle " + id); } else { events.onRemoteJsep(id, jsep); } } @Override public void error(String reason, String code) { //fixme: retry Log.e(TAG,"Transaction error: " + code + " " + reason); reportError(reason); } }; transactionMap.put(JanusTransaction2.transactionId, JanusTransaction2); JSONObject json = new JSONObject(); JSONObject jsonBody = new JSONObject(); jsonPut(jsonBody, "request", "configure"); jsonPut(jsonBody, "audio", true); jsonPut(jsonBody, "video", true); jsonPut(json, "janus", "message"); jsonPut(json, "body", jsonBody); jsonPut(json, "jsep", convertSdpToJson(sdp)); jsonPut(json, "session_id", sessionId); jsonPut(json, "handle_id", handleId); jsonPut(json, "transaction", JanusTransaction2.transactionId); wsClient.send(json.toString()); } private void createAnswer(BigInteger handleId, SessionDescription sdp) { checkIfCalledOnValidThread(); if(state != JanusServerState.CONNECTED) { Log.w(TAG, "join() in a error state -- " + state); return; } JanusTransaction2 JanusTransaction2 = new JanusTransaction2(); JanusTransaction2.transactionId = randomString(12); JanusTransaction2.events = new JanusTransaction2.TransactionEvents() { @Override public void success(BigInteger id) { reportNotification("Server receive the answer message in handle " + id); } @Override public void error(String reason, String code) { //fixme: retry Log.e(TAG,"Transaction error: " + code + " " + reason); reportError(reason); } }; transactionMap.put(JanusTransaction2.transactionId, JanusTransaction2); JSONObject json = new JSONObject(); JSONObject jsonBody = new JSONObject(); jsonPut(jsonBody, "request", "start"); jsonPut(jsonBody, "room", connectionParameters.roomId); jsonPut(json, "janus", "message"); jsonPut(json, "body", jsonBody); jsonPut(json, "jsep", convertSdpToJson(sdp)); jsonPut(json, "session_id", sessionId); jsonPut(json, "handle_id", handleId); jsonPut(json, "transaction", JanusTransaction2.transactionId); wsClient.send(json.toString()); } private void trickle(BigInteger handleId, IceCandidate iceCandidate) { checkIfCalledOnValidThread(); if(state != JanusServerState.CONNECTED) { Log.w(TAG, "keepalive() in a error state -- " + state); return; } JSONObject json = new JSONObject(); jsonPut(json, "janus", "trickle"); jsonPut(json, "candidate", convertJsonToCandidate(iceCandidate)); jsonPut(json, "session_id", sessionId); jsonPut(json, "handle_id", handleId); jsonPut(json, "transaction", randomString(12)); wsClient.send(json.toString()); } private void trickleComplete(BigInteger handleId) { checkIfCalledOnValidThread(); if(state != JanusServerState.CONNECTED) { Log.w(TAG, "keepalive() in a error state -- " + state); return; } JSONObject json = new JSONObject(); JSONObject jsonCandidate = new JSONObject(); jsonPut(jsonCandidate, "completed", true); jsonPut(json, "janus", "trickle"); jsonPut(json, "candidate", jsonCandidate); jsonPut(json, "session_id", sessionId); jsonPut(json, "handle_id", handleId); jsonPut(json, "transaction", randomString(12)); wsClient.send(json.toString()); } private void detach(final BigInteger handleId) { checkIfCalledOnValidThread(); if(state != JanusServerState.CONNECTED) { Log.w(TAG, "detach() in a error state -- " + state); return; } events.onLeft(handleId); JanusTransaction2 JanusTransaction2 = new JanusTransaction2(); JanusTransaction2.transactionId = randomString(12); JanusTransaction2.events = new JanusTransaction2.TransactionEvents() { @Override public void success(BigInteger id) { Log.d(TAG, "detach a handle by remote stream " + handleId); } @Override public void error(String reason, String code) { //fixme: retry Log.e(TAG,"Transaction error: " + code + " " + reason); } }; transactionMap.put(JanusTransaction2.transactionId, JanusTransaction2); JSONObject json = new JSONObject(); jsonPut(json, "janus", "detach"); jsonPut(json, "session_id", sessionId); jsonPut(json, "handle_id", handleId); jsonPut(json, "transaction", JanusTransaction2.transactionId); wsClient.send(json.toString()); // free some object JanusHandle janusHandle = handleMap.get(handleId); if(janusHandle == null) return; feedMap.remove(janusHandle.feedId); handleMap.remove(janusHandle.handleId); } private void destroy() { checkIfCalledOnValidThread(); if(sessionId == BigInteger.ZERO) { Log.w(TAG, "destroy() for sessionid 0"); return; } JSONObject json = new JSONObject(); jsonPut(json, "janus", "destroy"); jsonPut(json, "session_id", sessionId); jsonPut(json, "transaction", randomString(12)); wsClient.send(json.toString()); setState(JanusServerState.CLOSED); sessionId = BigInteger.ZERO; } private void disconnect() { destroy(); transactionMap.clear(); handleMap.clear(); feedMap.clear(); if (wsClient != null) { wsClient.disconnect(true); } } // ---------------------------------------------------------------------------- // / WebSocketChannelEvents interface implementation. // / All events are called by WebSocketChannelClient on a local looper thread // / (passed to WebSocket client constructor). // ---------------------------------------------------------------------------- @Override public void onWebSocketMessage(final String msg) { if (wsClient.getState() != WebSocketChannelClient.WebSocketConnectionState.CONNECTED) { Log.e(TAG, "onWebSocketMessage: got WebSocket message in error state."); return; } String transaction = null; Boolean isAck = false; try { JSONObject json = new JSONObject(msg); String janus = json.optString("janus"); String sender = json.optString("sender"); transaction = json.optString("transaction"); JanusTransaction2 JanusTransaction2 = transactionMap.get(transaction); // this branch will handle sender message, include server notification and server response. if(!sender.equals("")) { BigInteger senderId = new BigInteger(sender); if (janus.equals("event")) { JSONObject data = json.optJSONObject("plugindata").optJSONObject("data"); JSONArray publishers = data.optJSONArray("publishers"); if (publishers != null && publishers.length() > 0) { for (int i = 0; i < publishers.length(); i++) { JSONObject publisher = publishers.optJSONObject(i); BigInteger feedId = new BigInteger(publisher.optString("id")); String display = publisher.optString("display"); attach(feedId, display); } } String videoroom = data.optString("videoroom"); if (videoroom.equals("joined")) { String pid = data.optString("private_id"); if(!pid.equals("")) privateId = new BigInteger(pid); JanusTransaction2.events.success(senderId); } else if (videoroom.equals("attached")) { JanusTransaction2.events.success(senderId, json.optJSONObject("jsep")); } else if (videoroom.equals("event")) { String configured = data.optString("configured"); if(!configured.equals("") && JanusTransaction2 != null && JanusTransaction2.events != null) { if(configured.equals("ok")) { JanusTransaction2.events.success(senderId, json.optJSONObject("jsep")); }else { json = json.optJSONObject("error"); JanusTransaction2.events.error( checkError(json, "reason", "configured is " + configured), checkError(json, "code", "createOffer") ); } return; } String started = data.optString("started"); if(!started.equals("") && JanusTransaction2 != null && JanusTransaction2.events != null) { if(started.equals("ok")) { JanusTransaction2.events.success(senderId); } else { json = json.optJSONObject("error"); JanusTransaction2.events.error( checkError(json, "reason", "started is " + started), checkError(json, "code", "createAnswer") ); } return; } String unpublished = data.optString("unpublished"); if(!unpublished.equals("")) { if (unpublished.equals("ok")) { //fixme: this branch is unused, add function later. } else { BigInteger id = feedMap.get(new BigInteger(unpublished)); if(id != null) detach(id); } return; } String leaving = data.optString("leaving"); if (!leaving.equals("")) { BigInteger id = feedMap.get(new BigInteger(leaving)); if(id != null) detach(id); return; } } else if (videoroom.equals("slow_link")) { reportNotification("onWebSocketMessage: Got a slow_link event on session " + sessionId); } else if (videoroom.equals("error")) { if (JanusTransaction2 != null && JanusTransaction2.events != null) { JanusTransaction2.events.error("unknown error", "videoroom"); } } else { reportError("onWebSocketMessage: unrecognized protocol."); } } else if (janus.equals("webrtcup")) { reportNotification("onWebSocketMessage: webrtc peerConnection is up now."); } else if (janus.equals("slowlink")) { reportNotification("onWebSocketMessage: Got a slowlink event on session " + sessionId); } else if (janus.equals("media")) { reportNotification("onWebSocketMessage: Got a media event on session " + sessionId + ", media type is " + json.optString("type") + ", receiving is " + json.optBoolean("receiving")); } else if (janus.equals("hangup")) { Log.d(TAG, "onWebSocketMessage: Got a hangup event on session " + sessionId + ", feedid is " + sender); } else if (janus.equals("detached")) { //detach(senderId); } else if (janus.equals("error")) { json = json.optJSONObject("error"); if (JanusTransaction2 != null && JanusTransaction2.events != null && json != null) { String reason = json.optString("reason"); String code = json.optString("code"); JanusTransaction2.events.error(reason, code); } } else { reportError("onWebSocketMessage: unrecognized protocol."); } return; } // this branch will handle basic message if(janus.equals("ack")) { // Just an ack, we can probably ignore Log.i(TAG,"Got an ack on session " + sessionId); isAck = true; }else if(janus.equals("success")) { if (JanusTransaction2 != null && JanusTransaction2.events != null) { json = json.optJSONObject("data"); if(json != null) { String id = json.optString("id"); JanusTransaction2.events.success(new BigInteger(id)); } else { JanusTransaction2.events.success(BigInteger.ZERO); } } } else if(janus.equals("error")) { // something wrong happened json = json.optJSONObject("error"); if(json == null) return; String reason = json.optString("reason"); String code = json.optString("code"); if(JanusTransaction2 == null || JanusTransaction2.events == null) { Log.e(TAG, "onWebSocketMessage:error, Code:" + code + ", reason: " + reason); } else { JanusTransaction2.events.error(reason, code); } } else { Log.d(TAG, "onWebSocketMessage: unrecognized protocol."); } } catch (JSONException e) { reportError("WebSocket message JSON parsing error: " + e.toString()); } finally { if(!isAck) transactionMap.remove(transaction); } } @Override public void onWebSocketOpen() { create(); } @Override public void onWebSocketClose() { events.onChannelClose(); } @Override public void onWebSocketError(String description) { reportError("WebSocket error: " + description); } // ---------------------------------------------------------------------------- // Helper functions. // ---------------------------------------------------------------------------- private void checkIfCalledOnValidThread() { if (Thread.currentThread() != handler.getLooper().getThread()) { throw new IllegalStateException("WebSocket method is not called on valid thread"); } } private void setState(JanusServerState state) { if(state != JanusServerState.ERROR) this.state = state; } private String checkError(JSONObject json, String checkMessage, String defaultMessage) { if (json == null) return defaultMessage; else { String res = json.optString(checkMessage); return res.equals("") ? defaultMessage : res; } } private void reportError(final String errorMessage) { Log.e(TAG, errorMessage); handler.post(new Runnable() { @Override public void run() { if (state != JanusServerState.ERROR) { destroy(); setState(JanusServerState.ERROR); events.onChannelError(errorMessage); } } }); } private void reportNotification(final String notificationMessage) { } }
package com.tesco.encryptionservice.ssh.parser.decode; import com.tesco.encryptionservice.ssh.certificate.EcdsaSshCertificate; import lombok.SneakyThrows; public class Ecdsa521SshCertificateDecoder extends EcdsaSshCertificateDecoder<EcdsaSshCertificate> { private static final String CERTIFICATE_ALGORITHM = "ecdsa-sha2-nistp521-cert-v01@openssh.com"; private static final String ELLIPTIC_CURVE_KEY_STANDARD = "secp521r1"; @Override @SneakyThrows public EcdsaSshCertificate decode(byte[] bytes) { return decode(bytes, CERTIFICATE_ALGORITHM, ELLIPTIC_CURVE_KEY_STANDARD); } }
package me.bscal.healthy.common.registry; import me.bscal.healthy.Healthy; import me.bscal.healthy.common.blocks.UnlitTorch; import me.bscal.healthy.common.blocks.UnlitWallTorch; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.block.Block; import net.minecraft.block.Material; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; public class BlockRegistry { public static final Block UNLIT_TORCH = new UnlitTorch( FabricBlockSettings.of(Material.STRUCTURE_VOID)); public static final Block UNLIT_WALL_TORCH = new UnlitWallTorch( FabricBlockSettings.of(Material.STRUCTURE_VOID)); public static void Register() { Registry.register(Registry.BLOCK, new Identifier(Healthy.MOD_ID, "unlit_torch"), UNLIT_TORCH); Registry.register(Registry.BLOCK, new Identifier(Healthy.MOD_ID, "unlit_wall_torch"), UNLIT_WALL_TORCH); //((ResourceGenerators.Block) UNLIT_TORCH).client(Healthy.RESOURCE_PACK, new Identifier(Healthy.MOD_ID, "unlit_torch")); //((ResourceGenerators.Block) UNLIT_WALL_TORCH).client(Healthy.RESOURCE_PACK, new Identifier(Healthy.MOD_ID, "unlit_wall_torch")); // Healthy.RESOURCE_PACK.addLootTable(id(Healthy.MOD_ID, "unlit_torch"), // loot(NAMESPACE).pool(pool().rolls(1) // .entry(entry().type(NAMESPACE)) // .condition(predicate("minecraft:survives_explosion")))); } }
package org.digitalcrafting.theOne.service.users.dataaccess.discovery; import lombok.Data; @Data public class DiscoveryRegisterServiceRequest { private String serviceName; private String serviceIp; private String servicePort; }
package com.xaeport.cinsight.ui.common; import com.fasterxml.jackson.databind.util.ISO8601DateFormat; import com.fasterxml.jackson.databind.util.ISO8601Utils; import java.text.FieldPosition; import java.util.Date; public class RFC3339DateFormat extends ISO8601DateFormat { // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { String value = ISO8601Utils.format(date, true); toAppendTo.append(value); return toAppendTo; } }
package de.kaliburg.morefair.chat; import de.kaliburg.morefair.ladder.Ladder; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface MessageRepository extends JpaRepository<Message, Long> { // can't do limiting Queries ??? //@Query("SELECT m FROM Message m WHERE m.ladder = :ladder ORDER BY m.createdOn DESC") List<Message> findTop30ByLadderOrderByCreatedOnDesc(Ladder ladder); }
package tapl.nat; import java.util.Optional; public interface Pred<Elem, Tm, UNat> extends UnaryNat<Elem, Tm, UNat> { tapl.Term<Elem, Tm> getOf(); default Pred<Elem, Tm, UNat> replaceOf(tapl.Term<Elem, Tm> by) { return pred(by); } @Override default tapl.Term<Elem, Tm> eval() { Term<Elem, Tm, UNat> evaluatedInner = convert(getOf().eval()); if (evaluatedInner != getOf()) { return replaceOf(evaluatedInner); } Optional<? extends UnaryNat<Elem, Tm, UNat>> inner = evaluatedInner.matchUnaryNat(); return inner.filter(Term::isNumericValue).map(UnaryNat::predecessor).orElse(this); } @Override default String printDecimal(int offset) { // Wrong in the EVF tapl: need to add offset-many succs StringBuilder result = new StringBuilder(String.format("pred(%s)", getOf().print())); for (int i = 0; i < offset; ++i) { result = new StringBuilder("succ(").append(result).append(")"); } return result.toString(); } @Override default tapl.Term<Elem, Tm> predecessor() { return pred(this); } }
package net.teamfruit.mchelishield.asm; import java.util.Map; import javax.annotation.Nullable; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; public class PrivacyShieldCorePlugin implements IFMLLoadingPlugin { @Override public @Nullable String[] getASMTransformerClass() { return new String[] { PrivacyShieldTransformer.class.getName() }; } @Override public @Nullable String getModContainerClass() { return null; } @Override public @Nullable String getSetupClass() { return null; } @Override public void injectData(final @Nullable Map<String, Object> data) { } @Override public @Nullable String getAccessTransformerClass() { return null; } }
/** * 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. * * Copyright 2012-2017 the original author or authors. */ package org.assertj.core.internal; import static java.lang.Math.abs; import org.assertj.core.util.VisibleForTesting; /** * Reusable assertions for <code>{@link Double}</code>s. * * @author Drummond Dawson * @author Alex Ruiz * @author Joel Costigliola */ public class Doubles extends RealNumbers<Double> { private static final Doubles INSTANCE = new Doubles(); /** * Returns the singleton instance of this class based on {@link StandardComparisonStrategy}. * * @return the singleton instance of this class based on {@link StandardComparisonStrategy}. */ public static Doubles instance() { return INSTANCE; } @VisibleForTesting Doubles() { super(); } public Doubles(ComparisonStrategy comparisonStrategy) { super(comparisonStrategy); } @Override protected Double zero() { return 0.0d; } @Override protected Double one() { return 1.0d; } @Override protected Double NaN() { return Double.NaN; } @Override protected Double absDiff(Double actual, Double other) { return abs(other.doubleValue() - actual.doubleValue()); } }
/* * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.vault.config.databases; import org.springframework.cloud.vault.config.VaultSecretBackendDescriptor; /** * Configuration properties interface for database secrets. * * @author Mark Paluch * @author Sebastien Nahelou */ public interface DatabaseSecretProperties extends VaultSecretBackendDescriptor { /** * Role name. * @return the role name */ String getRole(); /** * Whether the configuration uses static roles. * @return {@literal true} if the configuration uses static roles. * @since 2.2 */ boolean isStaticRole(); /** * Backend path. * @return the backend path. */ String getBackend(); /** * @return name of the target property for the obtained username. */ String getUsernameProperty(); /** * @return name of the target property for the obtained password. */ String getPasswordProperty(); }
/* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.config.update; import com.thoughtworks.go.config.*; import com.thoughtworks.go.server.domain.Username; import com.thoughtworks.go.server.service.EntityHashingService; import com.thoughtworks.go.server.service.ExternalArtifactsService; import com.thoughtworks.go.server.service.SecurityService; import com.thoughtworks.go.server.service.result.LocalizedOperationResult; public class UpdateTemplateAuthConfigCommand extends UpdateTemplateConfigCommand { private final Authorization authorization; public UpdateTemplateAuthConfigCommand(PipelineTemplateConfig templateConfig, Authorization authorization, Username currentUser, SecurityService securityService, LocalizedOperationResult result, String md5, EntityHashingService entityHashingService, ExternalArtifactsService externalArtifactsService) { super(templateConfig, currentUser, securityService, result, md5, entityHashingService, externalArtifactsService); this.authorization = authorization; } @Override public void update(CruiseConfig modifiedConfig) { PipelineTemplateConfig existingTemplateConfig = findAddedTemplate(modifiedConfig); existingTemplateConfig.setAuthorization(authorization); } @Override public void encrypt(CruiseConfig preProcessedConfig) { } @Override public boolean isValid(CruiseConfig preprocessedConfig) { TemplatesConfig templates = preprocessedConfig.getTemplates(); preprocessedTemplateConfig = findAddedTemplate(preprocessedConfig); preprocessedTemplateConfig.getAuthorization().validateTree(new DelegatingValidationContext(ConfigSaveValidationContext.forChain(preprocessedConfig, templates)) { @Override public boolean shouldNotCheckRole() { return false; } }); if (!preprocessedTemplateConfig.getAuthorization().getAllErrors().isEmpty()) { BasicCruiseConfig.copyErrors(preprocessedTemplateConfig.getAuthorization(), authorization); return false; } return true; } }
package zhang.springframework.gof.abstractFactory.topping; public class GoatCheese implements Cheese { public GoatCheese(){ prepareCheese(); } @Override public void prepareCheese(){ System.out.println("Preparing goat cheese..."); } }
/* * 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.dtstack.flinkx.metrics; import com.dtstack.flinkx.constants.Metrics; import com.dtstack.flinkx.util.SysUtil; import org.apache.flink.api.common.accumulators.LongCounter; import org.apache.flink.api.common.functions.RuntimeContext; import org.apache.flink.metrics.MetricGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * @author jiangbo * @date 2019/6/5 */ public class BaseMetric { protected final Logger LOG = LoggerFactory.getLogger(getClass()); private Long delayPeriodMill = 20000L; private MetricGroup flinkxOutput; private final Map<String, LongCounter> metricCounters = new HashMap<>(); public BaseMetric(RuntimeContext runtimeContext) { flinkxOutput = runtimeContext.getMetricGroup().addGroup(Metrics.METRIC_GROUP_KEY_FLINKX, Metrics.METRIC_GROUP_VALUE_OUTPUT); } public void addMetric(String metricName, LongCounter counter){ addMetric(metricName, counter, false); } public void addMetric(String metricName, LongCounter counter, boolean meterView){ metricCounters.put(metricName, counter); flinkxOutput.gauge(metricName, new SimpleAccumulatorGauge<>(counter)); if (meterView){ flinkxOutput.meter(metricName + Metrics.SUFFIX_RATE, new SimpleLongCounterMeterView(counter, 60)); } } public Map<String, LongCounter> getMetricCounters() { return metricCounters; } public void waitForReportMetrics() { try { Thread.sleep(delayPeriodMill); } catch (InterruptedException e){ SysUtil.sleep(delayPeriodMill); LOG.warn("Task thread is interrupted"); } } }
import java.io.*; import java.io.PrintWriter; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/Login") public class Login extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); /* User Information(username,password,usertype) is obtained from HttpServletRequest, Based on the Type of user(customer,retailer,manager) respective hashmap is called and the username and password are validated and added to session variable and display Login Function is called */ String username = request.getParameter("username"); String password = request.getParameter("password"); String usertype = request.getParameter("usertype"); HashMap<String, User> hm=new HashMap<String, User>(); String TOMCAT_HOME = System.getProperty("catalina.home"); //user details are validated using a file //if the file containts username and passoword user entered user will be directed to home page //else error message will be shown try { FileInputStream fileInputStream = new FileInputStream(new File(TOMCAT_HOME+"\\webapps\\assignment1\\UserDetails.txt")); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); hm = (HashMap)objectInputStream.readObject(); } catch(Exception e) { } User user = hm.get(username); if(user!=null) { String user_password = user.getPassword(); if (password.equals(user_password) && usertype.equals(user.getUsertype())) { HttpSession session = request.getSession(true); session.setAttribute("username", user.getName()); session.setAttribute("usertype", user.getUsertype()); response.sendRedirect("Home"); return; } } displayLogin(request, response, pw, true); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); displayLogin(request, response, pw, false); } /* Login Screen is Displayed, Registered User specifies credentials and logins into the Game Speed Application. */ protected void displayLogin(HttpServletRequest request, HttpServletResponse response, PrintWriter pw, boolean error) throws ServletException, IOException { Utilities utility = new Utilities(request, pw); utility.printHtml("Header.html"); pw.print("<div class='post' style='float: none; width: 100%'>"); pw.print("<h2 class='title meta'><a style='font-size: 24px;'>Login</a></h2>" + "<div class='entry'>" + "<div style='width:400px; margin:25px; margin-left: auto;margin-right: auto;'>"); if (error) pw.print("<h4 style='color:red'>Please check your username, password and user type!</h4>"); HttpSession session = request.getSession(true); if(session.getAttribute("login_msg")!=null){ pw.print("<h4 style='color:red'>"+session.getAttribute("login_msg")+"</h4>"); session.removeAttribute("login_msg"); } pw.print("<form method='post' action='Login'>" + "<table style='width:100%'><tr><td>" + "<h3>Username</h3></td><td><input type='text' name='username' value='' class='input' required></input>" + "</td></tr><tr><td>" + "<h3>Password</h3></td><td><input type='password' name='password' value='' class='input' required></input>" + "</td></tr><tr><td>" + "<h3>User Type</h3></td><td><select name='usertype' class='input'><option value='customer' selected>Customer</option><option value='manager'>Store Manager</option><option value='retailer'>Salesman</option></select>" + "</td></tr><tr><td></td><td>" + "<input type='submit' class='btnbuy' value='Login' style='float: right;height: 20px margin: 20px; margin-right: 10px;'></input>" + "</td></tr><tr><td></td><td>" + "<strong><a class='' href='Registration' style='float: right;height: 20px margin: 20px;'>New User? Register here!</a></strong>" + "</td></tr></table>" + "</form>" + "</div></div></div>"); utility.printHtml("Footer.html"); } }
package com.ziroom.tech.demeterapi.dao.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * <pre> * ━━━━━━神兽出没━━━━━━ *    ┏┓   ┏┓ *   ┏┛┻━━━┛┻┓ *   ┃       ┃ *   ┃   ━   ┃ *   ┃ ┳┛ ┗┳ ┃ *   ┃       ┃ *   ┃   ┻   ┃ *   ┃       ┃ *   ┗━┓   ┏━┛ *     ┃   ┃神兽保佑, 永无BUG! *     ┃   ┃Code is far away from bug with the animal protecting *     ┃   ┗━━━┓ *     ┃       ┣┓ *     ┃       ┏┛ *     ┗┓┓┏━┳┓┏┛ *      ┃┫┫ ┃┫┫ *      ┗┻┛ ┗┻┛ * ━━━━━━感觉萌萌哒━━━━━━ * </pre> */ public class TaskFinishOutcomeExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public TaskFinishOutcomeExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * <pre> * ━━━━━━神兽出没━━━━━━ *    ┏┓   ┏┓ *   ┏┛┻━━━┛┻┓ *   ┃       ┃ *   ┃   ━   ┃ *   ┃ ┳┛ ┗┳ ┃ *   ┃       ┃ *   ┃   ┻   ┃ *   ┃       ┃ *   ┗━┓   ┏━┛ *     ┃   ┃神兽保佑, 永无BUG! *     ┃   ┃Code is far away from bug with the animal protecting *     ┃   ┗━━━┓ *     ┃       ┣┓ *     ┃       ┏┛ *     ┗┓┓┏━┳┓┏┛ *      ┃┫┫ ┃┫┫ *      ┗┻┛ ┗┻┛ * ━━━━━━感觉萌萌哒━━━━━━ * </pre> */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Long> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Long> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andFileAddressIsNull() { addCriterion("file_address is null"); return (Criteria) this; } public Criteria andFileAddressIsNotNull() { addCriterion("file_address is not null"); return (Criteria) this; } public Criteria andFileAddressEqualTo(String value) { addCriterion("file_address =", value, "fileAddress"); return (Criteria) this; } public Criteria andFileAddressNotEqualTo(String value) { addCriterion("file_address <>", value, "fileAddress"); return (Criteria) this; } public Criteria andFileAddressGreaterThan(String value) { addCriterion("file_address >", value, "fileAddress"); return (Criteria) this; } public Criteria andFileAddressGreaterThanOrEqualTo(String value) { addCriterion("file_address >=", value, "fileAddress"); return (Criteria) this; } public Criteria andFileAddressLessThan(String value) { addCriterion("file_address <", value, "fileAddress"); return (Criteria) this; } public Criteria andFileAddressLessThanOrEqualTo(String value) { addCriterion("file_address <=", value, "fileAddress"); return (Criteria) this; } public Criteria andFileAddressLike(String value) { addCriterion("file_address like", value, "fileAddress"); return (Criteria) this; } public Criteria andFileAddressNotLike(String value) { addCriterion("file_address not like", value, "fileAddress"); return (Criteria) this; } public Criteria andFileAddressIn(List<String> values) { addCriterion("file_address in", values, "fileAddress"); return (Criteria) this; } public Criteria andFileAddressNotIn(List<String> values) { addCriterion("file_address not in", values, "fileAddress"); return (Criteria) this; } public Criteria andFileAddressBetween(String value1, String value2) { addCriterion("file_address between", value1, value2, "fileAddress"); return (Criteria) this; } public Criteria andFileAddressNotBetween(String value1, String value2) { addCriterion("file_address not between", value1, value2, "fileAddress"); return (Criteria) this; } public Criteria andFileNameIsNull() { addCriterion("file_name is null"); return (Criteria) this; } public Criteria andFileNameIsNotNull() { addCriterion("file_name is not null"); return (Criteria) this; } public Criteria andFileNameEqualTo(String value) { addCriterion("file_name =", value, "fileName"); return (Criteria) this; } public Criteria andFileNameNotEqualTo(String value) { addCriterion("file_name <>", value, "fileName"); return (Criteria) this; } public Criteria andFileNameGreaterThan(String value) { addCriterion("file_name >", value, "fileName"); return (Criteria) this; } public Criteria andFileNameGreaterThanOrEqualTo(String value) { addCriterion("file_name >=", value, "fileName"); return (Criteria) this; } public Criteria andFileNameLessThan(String value) { addCriterion("file_name <", value, "fileName"); return (Criteria) this; } public Criteria andFileNameLessThanOrEqualTo(String value) { addCriterion("file_name <=", value, "fileName"); return (Criteria) this; } public Criteria andFileNameLike(String value) { addCriterion("file_name like", value, "fileName"); return (Criteria) this; } public Criteria andFileNameNotLike(String value) { addCriterion("file_name not like", value, "fileName"); return (Criteria) this; } public Criteria andFileNameIn(List<String> values) { addCriterion("file_name in", values, "fileName"); return (Criteria) this; } public Criteria andFileNameNotIn(List<String> values) { addCriterion("file_name not in", values, "fileName"); return (Criteria) this; } public Criteria andFileNameBetween(String value1, String value2) { addCriterion("file_name between", value1, value2, "fileName"); return (Criteria) this; } public Criteria andFileNameNotBetween(String value1, String value2) { addCriterion("file_name not between", value1, value2, "fileName"); return (Criteria) this; } public Criteria andTaskIdIsNull() { addCriterion("task_id is null"); return (Criteria) this; } public Criteria andTaskIdIsNotNull() { addCriterion("task_id is not null"); return (Criteria) this; } public Criteria andTaskIdEqualTo(Long value) { addCriterion("task_id =", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdNotEqualTo(Long value) { addCriterion("task_id <>", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdGreaterThan(Long value) { addCriterion("task_id >", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdGreaterThanOrEqualTo(Long value) { addCriterion("task_id >=", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdLessThan(Long value) { addCriterion("task_id <", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdLessThanOrEqualTo(Long value) { addCriterion("task_id <=", value, "taskId"); return (Criteria) this; } public Criteria andTaskIdIn(List<Long> values) { addCriterion("task_id in", values, "taskId"); return (Criteria) this; } public Criteria andTaskIdNotIn(List<Long> values) { addCriterion("task_id not in", values, "taskId"); return (Criteria) this; } public Criteria andTaskIdBetween(Long value1, Long value2) { addCriterion("task_id between", value1, value2, "taskId"); return (Criteria) this; } public Criteria andTaskIdNotBetween(Long value1, Long value2) { addCriterion("task_id not between", value1, value2, "taskId"); return (Criteria) this; } public Criteria andTaskTypeIsNull() { addCriterion("task_type is null"); return (Criteria) this; } public Criteria andTaskTypeIsNotNull() { addCriterion("task_type is not null"); return (Criteria) this; } public Criteria andTaskTypeEqualTo(Integer value) { addCriterion("task_type =", value, "taskType"); return (Criteria) this; } public Criteria andTaskTypeNotEqualTo(Integer value) { addCriterion("task_type <>", value, "taskType"); return (Criteria) this; } public Criteria andTaskTypeGreaterThan(Integer value) { addCriterion("task_type >", value, "taskType"); return (Criteria) this; } public Criteria andTaskTypeGreaterThanOrEqualTo(Integer value) { addCriterion("task_type >=", value, "taskType"); return (Criteria) this; } public Criteria andTaskTypeLessThan(Integer value) { addCriterion("task_type <", value, "taskType"); return (Criteria) this; } public Criteria andTaskTypeLessThanOrEqualTo(Integer value) { addCriterion("task_type <=", value, "taskType"); return (Criteria) this; } public Criteria andTaskTypeIn(List<Integer> values) { addCriterion("task_type in", values, "taskType"); return (Criteria) this; } public Criteria andTaskTypeNotIn(List<Integer> values) { addCriterion("task_type not in", values, "taskType"); return (Criteria) this; } public Criteria andTaskTypeBetween(Integer value1, Integer value2) { addCriterion("task_type between", value1, value2, "taskType"); return (Criteria) this; } public Criteria andTaskTypeNotBetween(Integer value1, Integer value2) { addCriterion("task_type not between", value1, value2, "taskType"); return (Criteria) this; } public Criteria andReceiverUidIsNull() { addCriterion("receiver_uid is null"); return (Criteria) this; } public Criteria andReceiverUidIsNotNull() { addCriterion("receiver_uid is not null"); return (Criteria) this; } public Criteria andReceiverUidEqualTo(String value) { addCriterion("receiver_uid =", value, "receiverUid"); return (Criteria) this; } public Criteria andReceiverUidNotEqualTo(String value) { addCriterion("receiver_uid <>", value, "receiverUid"); return (Criteria) this; } public Criteria andReceiverUidGreaterThan(String value) { addCriterion("receiver_uid >", value, "receiverUid"); return (Criteria) this; } public Criteria andReceiverUidGreaterThanOrEqualTo(String value) { addCriterion("receiver_uid >=", value, "receiverUid"); return (Criteria) this; } public Criteria andReceiverUidLessThan(String value) { addCriterion("receiver_uid <", value, "receiverUid"); return (Criteria) this; } public Criteria andReceiverUidLessThanOrEqualTo(String value) { addCriterion("receiver_uid <=", value, "receiverUid"); return (Criteria) this; } public Criteria andReceiverUidLike(String value) { addCriterion("receiver_uid like", value, "receiverUid"); return (Criteria) this; } public Criteria andReceiverUidNotLike(String value) { addCriterion("receiver_uid not like", value, "receiverUid"); return (Criteria) this; } public Criteria andReceiverUidIn(List<String> values) { addCriterion("receiver_uid in", values, "receiverUid"); return (Criteria) this; } public Criteria andReceiverUidNotIn(List<String> values) { addCriterion("receiver_uid not in", values, "receiverUid"); return (Criteria) this; } public Criteria andReceiverUidBetween(String value1, String value2) { addCriterion("receiver_uid between", value1, value2, "receiverUid"); return (Criteria) this; } public Criteria andReceiverUidNotBetween(String value1, String value2) { addCriterion("receiver_uid not between", value1, value2, "receiverUid"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andModifyTimeIsNull() { addCriterion("modify_time is null"); return (Criteria) this; } public Criteria andModifyTimeIsNotNull() { addCriterion("modify_time is not null"); return (Criteria) this; } public Criteria andModifyTimeEqualTo(Date value) { addCriterion("modify_time =", value, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeNotEqualTo(Date value) { addCriterion("modify_time <>", value, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeGreaterThan(Date value) { addCriterion("modify_time >", value, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeGreaterThanOrEqualTo(Date value) { addCriterion("modify_time >=", value, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeLessThan(Date value) { addCriterion("modify_time <", value, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeLessThanOrEqualTo(Date value) { addCriterion("modify_time <=", value, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeIn(List<Date> values) { addCriterion("modify_time in", values, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeNotIn(List<Date> values) { addCriterion("modify_time not in", values, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeBetween(Date value1, Date value2) { addCriterion("modify_time between", value1, value2, "modifyTime"); return (Criteria) this; } public Criteria andModifyTimeNotBetween(Date value1, Date value2) { addCriterion("modify_time not between", value1, value2, "modifyTime"); return (Criteria) this; } public Criteria andCreateIdIsNull() { addCriterion("create_id is null"); return (Criteria) this; } public Criteria andCreateIdIsNotNull() { addCriterion("create_id is not null"); return (Criteria) this; } public Criteria andCreateIdEqualTo(String value) { addCriterion("create_id =", value, "createId"); return (Criteria) this; } public Criteria andCreateIdNotEqualTo(String value) { addCriterion("create_id <>", value, "createId"); return (Criteria) this; } public Criteria andCreateIdGreaterThan(String value) { addCriterion("create_id >", value, "createId"); return (Criteria) this; } public Criteria andCreateIdGreaterThanOrEqualTo(String value) { addCriterion("create_id >=", value, "createId"); return (Criteria) this; } public Criteria andCreateIdLessThan(String value) { addCriterion("create_id <", value, "createId"); return (Criteria) this; } public Criteria andCreateIdLessThanOrEqualTo(String value) { addCriterion("create_id <=", value, "createId"); return (Criteria) this; } public Criteria andCreateIdLike(String value) { addCriterion("create_id like", value, "createId"); return (Criteria) this; } public Criteria andCreateIdNotLike(String value) { addCriterion("create_id not like", value, "createId"); return (Criteria) this; } public Criteria andCreateIdIn(List<String> values) { addCriterion("create_id in", values, "createId"); return (Criteria) this; } public Criteria andCreateIdNotIn(List<String> values) { addCriterion("create_id not in", values, "createId"); return (Criteria) this; } public Criteria andCreateIdBetween(String value1, String value2) { addCriterion("create_id between", value1, value2, "createId"); return (Criteria) this; } public Criteria andCreateIdNotBetween(String value1, String value2) { addCriterion("create_id not between", value1, value2, "createId"); return (Criteria) this; } public Criteria andModifyIdIsNull() { addCriterion("modify_id is null"); return (Criteria) this; } public Criteria andModifyIdIsNotNull() { addCriterion("modify_id is not null"); return (Criteria) this; } public Criteria andModifyIdEqualTo(String value) { addCriterion("modify_id =", value, "modifyId"); return (Criteria) this; } public Criteria andModifyIdNotEqualTo(String value) { addCriterion("modify_id <>", value, "modifyId"); return (Criteria) this; } public Criteria andModifyIdGreaterThan(String value) { addCriterion("modify_id >", value, "modifyId"); return (Criteria) this; } public Criteria andModifyIdGreaterThanOrEqualTo(String value) { addCriterion("modify_id >=", value, "modifyId"); return (Criteria) this; } public Criteria andModifyIdLessThan(String value) { addCriterion("modify_id <", value, "modifyId"); return (Criteria) this; } public Criteria andModifyIdLessThanOrEqualTo(String value) { addCriterion("modify_id <=", value, "modifyId"); return (Criteria) this; } public Criteria andModifyIdLike(String value) { addCriterion("modify_id like", value, "modifyId"); return (Criteria) this; } public Criteria andModifyIdNotLike(String value) { addCriterion("modify_id not like", value, "modifyId"); return (Criteria) this; } public Criteria andModifyIdIn(List<String> values) { addCriterion("modify_id in", values, "modifyId"); return (Criteria) this; } public Criteria andModifyIdNotIn(List<String> values) { addCriterion("modify_id not in", values, "modifyId"); return (Criteria) this; } public Criteria andModifyIdBetween(String value1, String value2) { addCriterion("modify_id between", value1, value2, "modifyId"); return (Criteria) this; } public Criteria andModifyIdNotBetween(String value1, String value2) { addCriterion("modify_id not between", value1, value2, "modifyId"); return (Criteria) this; } } /** * <pre> * ━━━━━━神兽出没━━━━━━ *    ┏┓   ┏┓ *   ┏┛┻━━━┛┻┓ *   ┃       ┃ *   ┃   ━   ┃ *   ┃ ┳┛ ┗┳ ┃ *   ┃       ┃ *   ┃   ┻   ┃ *   ┃       ┃ *   ┗━┓   ┏━┛ *     ┃   ┃神兽保佑, 永无BUG! *     ┃   ┃Code is far away from bug with the animal protecting *     ┃   ┗━━━┓ *     ┃       ┣┓ *     ┃       ┏┛ *     ┗┓┓┏━┳┓┏┛ *      ┃┫┫ ┃┫┫ *      ┗┻┛ ┗┻┛ * ━━━━━━感觉萌萌哒━━━━━━ * </pre> */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * <pre> * ━━━━━━神兽出没━━━━━━ *    ┏┓   ┏┓ *   ┏┛┻━━━┛┻┓ *   ┃       ┃ *   ┃   ━   ┃ *   ┃ ┳┛ ┗┳ ┃ *   ┃       ┃ *   ┃   ┻   ┃ *   ┃       ┃ *   ┗━┓   ┏━┛ *     ┃   ┃神兽保佑, 永无BUG! *     ┃   ┃Code is far away from bug with the animal protecting *     ┃   ┗━━━┓ *     ┃       ┣┓ *     ┃       ┏┛ *     ┗┓┓┏━┳┓┏┛ *      ┃┫┫ ┃┫┫ *      ┗┻┛ ┗┻┛ * ━━━━━━感觉萌萌哒━━━━━━ * </pre> */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package org.ranji.lemon.volador.model.personal; import org.apache.ibatis.type.Alias; import org.ranji.lemon.core.model.AbstractModel; import org.ranji.lemon.core.util.JsonUtil; @Alias("VoladorInvitationCode") public class InvitationCode extends AbstractModel{ private static final long serialVersionUID = 1L; private String invitationCode; private int userId; public String getInvitationCode() { return invitationCode; } public void setInvitationCode(String invitationCode) { this.invitationCode = invitationCode; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public static long getSerialversionuid() { return serialVersionUID; } @Override public String toString(){ return JsonUtil.objectToJson(this); } }
package com.iso.dashboard.dto; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; @Entity @Table(name = "c_menu") public class CMenu implements Serializable { @Id // @Column(name = "ID") @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "c_menu_id", nullable = false) private Integer id; @Column(name = "CODE", nullable = false) private String code; @Column(name = "NAME", nullable = true) private String name; @Column(name = "PARENT_ID", nullable = true) private Integer parentId; @Column(name = "IS_ACTIVE", nullable = true) private Integer isActive; @Column(name = "IS_PARENT", nullable = true) private Integer isParent; @Column(name = "IS_CONTAIN_CHILD", nullable = true) private Integer isContainChild; @Column(name = "CREATE_TIME", nullable = true) @Temporal(javax.persistence.TemporalType.DATE) private Date createTime; public CMenu() { //contructor } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getParentId() { return parentId; } public void setParentId(Integer parentId) { this.parentId = parentId; } public Integer getIsActive() { return isActive; } public void setIsActive(Integer isActive) { this.isActive = isActive; } public Integer getIsParent() { return isParent; } public void setIsParent(Integer isParent) { this.isParent = isParent; } public Integer getIsContainChild() { return isContainChild; } public void setIsContainChild(Integer isContainChild) { this.isContainChild = isContainChild; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
package ca.uhn.fhir.jpa.searchparam.extractor; /* * #%L * HAPI FHIR Search Parameters * %% * Copyright (C) 2014 - 2021 Smile CDR, Inc. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jpa.model.config.PartitionSettings; import ca.uhn.fhir.jpa.model.entity.ModelConfig; import ca.uhn.fhir.rest.server.util.ISearchParamRegistry; import com.google.common.annotations.VisibleForTesting; import org.hl7.fhir.dstu3.context.IWorkerContext; import org.hl7.fhir.dstu3.hapi.ctx.HapiWorkerContext; import org.hl7.fhir.dstu3.model.Base; import org.hl7.fhir.dstu3.utils.FHIRPathEngine; import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBaseResource; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; public class SearchParamExtractorDstu3 extends BaseSearchParamExtractor implements ISearchParamExtractor { private FHIRPathEngine myFhirPathEngine; /** * Constructor */ public SearchParamExtractorDstu3() { super(); } // This constructor is used by tests @VisibleForTesting public SearchParamExtractorDstu3(ModelConfig theModelConfig, PartitionSettings thePartitionSettings, FhirContext theCtx, ISearchParamRegistry theSearchParamRegistry) { super(theModelConfig, thePartitionSettings, theCtx, theSearchParamRegistry); initFhirPathEngine(); start(); } @Override protected IValueExtractor getPathValueExtractor(IBaseResource theResource, String theSinglePath) { return () -> { List<IBase> values = new ArrayList<>(); List<Base> allValues = myFhirPathEngine.evaluate((Base) theResource, theSinglePath); if (allValues.isEmpty() == false) { values.addAll(allValues); } return values; }; } @Override @PostConstruct public void start() { super.start(); if (myFhirPathEngine == null) { initFhirPathEngine(); } } public void initFhirPathEngine() { IWorkerContext worker = new HapiWorkerContext(getContext(), getContext().getValidationSupport()); myFhirPathEngine = new FHIRPathEngine(worker); } }
/* * 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. */ /* Generated By:JJTree: Do not edit this line. AstString.java */ package org.apache.el.parser; import jakarta.el.ELException; import org.apache.el.lang.EvaluationContext; /** * @author Jacob Hookom [jacob@hookom.net] */ public final class AstString extends SimpleNode { public AstString(int id) { super(id); } private volatile String string; public String getString() { if (this.string == null) { this.string = this.image.substring(1, this.image.length() - 1); } return this.string; } @Override public Class<?> getType(EvaluationContext ctx) throws ELException { return String.class; } @Override public Object getValue(EvaluationContext ctx) throws ELException { return this.getString(); } @Override public void setImage(String image) { if (image.indexOf('\\') == -1) { this.image = image; return; } int size = image.length(); StringBuilder buf = new StringBuilder(size); for (int i = 0; i < size; i++) { char c = image.charAt(i); if (c == '\\' && i + 1 < size) { char c1 = image.charAt(i + 1); if (c1 == '\\' || c1 == '"' || c1 == '\'') { c = c1; i++; } } buf.append(c); } this.image = buf.toString(); } }
package WeatherApp; import java.util.ArrayList; import java.util.List; public class Observable { private List<Observer> observers = new ArrayList<>(); public void register(Observer observer){ System.out.println("going to register"); this.observers.add(observer); } public void deregsiter(Observer observer){ System.out.println("going to de register"); this.observers.remove(observer); } public void notifyChange(){ this.observers.forEach(x -> x.onUpdate()); } }
/* * Copyright (c) 2002-2017 Gargoyle Software 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.gargoylesoftware.htmlunit.html; import static com.gargoylesoftware.htmlunit.BrowserRunner.Browser.CHROME; import static org.junit.Assert.fail; import java.util.Collections; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.By; import org.openqa.selenium.InvalidElementStateException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import com.gargoylesoftware.htmlunit.BrowserRunner; import com.gargoylesoftware.htmlunit.BrowserRunner.Alerts; import com.gargoylesoftware.htmlunit.BrowserRunner.NotYetImplemented; import com.gargoylesoftware.htmlunit.WebDriverTestCase; /** * Tests for {@link HtmlTextInput}. * * @author Ronald Brill */ @RunWith(BrowserRunner.class) public class HtmlNumberInputTest extends WebDriverTestCase { /** * Verifies that a asText() returns an empty string. * @throws Exception if the test fails */ @Test @NotYetImplemented public void asText() throws Exception { final String htmlContent = "<html><head><title>foo</title></head><body>\n" + "<form id='form1'>\n" + " <input type='number' name='foo' id='foo' value='123'>\n" + "</form></body></html>"; final WebDriver driver = loadPage2(htmlContent); final WebElement input = driver.findElement(By.id("foo")); assertEquals("", input.getText()); } /** * @throws Exception if the test fails */ @Test public void type() throws Exception { final String html = "<html><head></head><body><input type='number' id='t'/></body></html>"; final WebDriver driver = loadPage2(html); final WebElement t = driver.findElement(By.id("t")); t.sendKeys("123"); assertEquals("123", t.getAttribute("value")); t.sendKeys("\b"); assertEquals("12", t.getAttribute("value")); t.sendKeys("\b"); assertEquals("1", t.getAttribute("value")); t.sendKeys("\b"); assertEquals("", t.getAttribute("value")); t.sendKeys("\b"); assertEquals("", t.getAttribute("value")); } /** * @throws Exception if the test fails */ @Test public void typeWhileDisabled() throws Exception { final String html = "<html><body><input type='number' id='p' disabled='disabled'/></body></html>"; final WebDriver driver = loadPage2(html); final WebElement p = driver.findElement(By.id("p")); try { p.sendKeys("abc"); fail(); } catch (final InvalidElementStateException e) { // as expected } assertEquals("", p.getAttribute("value")); } /** * @throws Exception if the test fails */ @Test @Alerts({"null", "null"}) @NotYetImplemented public void typeDoesNotChangeValueAttribute() throws Exception { final String html = "<html>\n" + "<head></head>\n" + "<body>\n" + " <input type='number' id='t'/>\n" + " <button id='check' onclick='alert(document.getElementById(\"t\").getAttribute(\"value\"));'>" + "DoIt</button>\n" + "</body></html>"; final WebDriver driver = loadPage2(html); final WebElement t = driver.findElement(By.id("t")); final WebElement check = driver.findElement(By.id("check")); check.click(); t.sendKeys("abc"); check.click(); verifyAlerts(driver, getExpectedAlerts()); } /** * @throws Exception if the test fails */ @Test @Alerts({"1234", "1234"}) @NotYetImplemented public void typeDoesNotChangeValueAttributeWithInitialValue() throws Exception { final String html = "<html>\n" + "<head></head>\n" + "<body>\n" + " <input type='number' id='t' value='1234'/>\n" + " <button id='check' onclick='alert(document.getElementById(\"t\").getAttribute(\"value\"));'>" + "DoIt</button>\n" + "</body></html>"; final WebDriver driver = loadPage2(html); final WebElement t = driver.findElement(By.id("t")); final WebElement check = driver.findElement(By.id("check")); check.click(); t.sendKeys("987"); check.click(); verifyAlerts(driver, getExpectedAlerts()); } /** * @throws Exception if an error occurs */ @Test public void preventDefault_OnKeyDown() throws Exception { final String html = "<html><head><script>\n" + " function handler(e) {\n" + " if (e && e.target.value.length > 2)\n" + " e.preventDefault();\n" + " else if (!e && window.event.srcElement.value.length > 2)\n" + " return false;\n" + " }\n" + " function init() {\n" + " document.getElementById('p').onkeydown = handler;\n" + " }\n" + "</script></head>\n" + "<body onload='init()'>\n" + "<input type='number' id='p'></input>\n" + "</body></html>"; final WebDriver driver = loadPage2(html); final WebElement p = driver.findElement(By.id("p")); p.sendKeys("1234"); assertEquals("123", p.getAttribute("value")); } /** * @throws Exception if an error occurs */ @Test public void preventDefault_OnKeyPress() throws Exception { final String html = "<html><head><script>\n" + " function handler(e) {\n" + " if (e && e.target.value.length > 2)\n" + " e.preventDefault();\n" + " else if (!e && window.event.srcElement.value.length > 2)\n" + " return false;\n" + " }\n" + " function init() {\n" + " document.getElementById('p').onkeypress = handler;\n" + " }\n" + "</script></head>\n" + "<body onload='init()'>\n" + "<input type='number' id='p'></input>\n" + "</body></html>"; final WebDriver driver = loadPage2(html); final WebElement p = driver.findElement(By.id("p")); p.sendKeys("1234"); assertEquals("123", p.getAttribute("value")); } /** * @throws Exception if an error occurs */ @Test public void typeOnChange() throws Exception { final String html = "<html><head></head><body>\n" + "<input type='number' id='p' value='1234'" + " onChange='alert(\"foo\");alert(event.type);'" + " onBlur='alert(\"boo\");alert(event.type);'>\n" + "<button id='b'>some button</button>\n" + "</body></html>"; final WebDriver driver = loadPage2(html); final WebElement p = driver.findElement(By.id("p")); p.sendKeys("567"); assertEquals(Collections.emptyList(), getCollectedAlerts(driver)); // trigger lost focus driver.findElement(By.id("b")).click(); final String[] expectedAlerts1 = {"foo", "change", "boo", "blur"}; assertEquals(expectedAlerts1, getCollectedAlerts(driver)); // set only the focus but change nothing p.click(); assertEquals(expectedAlerts1, getCollectedAlerts(driver)); // trigger lost focus driver.findElement(By.id("b")).click(); final String[] expectedAlerts2 = {"foo", "change", "boo", "blur", "boo", "blur"}; assertEquals(expectedAlerts2, getCollectedAlerts(driver)); } /** * @throws Exception if an error occurs */ @Test public void setValueOnChange() throws Exception { final String html = "<html>\n" + "<head></head>\n" + "<body>\n" + " <input type='number' id='t' value='1234'" + " onChange='alert(\"foo\");alert(event.type);'>\n" + " <button id='b'>some button</button>\n" + " <button id='set' onclick='document.getElementById(\"t\").value=\"1234\"'>setValue</button>\n" + "</body></html>"; final WebDriver driver = loadPage2(html); driver.findElement(By.id("set")).click(); assertEquals(Collections.emptyList(), getCollectedAlerts(driver)); // trigger lost focus driver.findElement(By.id("b")).click(); assertEquals(Collections.emptyList(), getCollectedAlerts(driver)); } /** * @throws Exception if an error occurs */ @Test public void setDefaultValueOnChange() throws Exception { final String html = "<html>\n" + "<head></head>\n" + "<body>\n" + " <input type='number' id='t' value='1234'" + " onChange='alert(\"foo\");alert(event.type);'>\n" + " <button id='b'>some button</button>\n" + " <button id='set' onclick='document.getElementById(\"t\").defaultValue=\"1234\"'>" + "setValue</button>\n" + "</body></html>"; final WebDriver driver = loadPage2(html); driver.findElement(By.id("set")).click(); assertEquals(Collections.emptyList(), getCollectedAlerts(driver)); // trigger lost focus driver.findElement(By.id("b")).click(); assertEquals(Collections.emptyList(), getCollectedAlerts(driver)); } /** * @throws Exception if the test fails */ @Test @Alerts({"--null", "--null", "--null"}) public void defaultValues() throws Exception { final String html = "<html><head><title>foo</title>\n" + "<script>\n" + " function test() {\n" + " var input = document.getElementById('text1');\n" + " alert(input.value + '-' + input.defaultValue + '-' + input.getAttribute('value'));\n" + " input = document.createElement('input');\n" + " input.type = 'number';\n" + " alert(input.value + '-' + input.defaultValue + '-' + input.getAttribute('value'));\n" + " var builder = document.createElement('div');\n" + " builder.innerHTML = '<input type=\"text\">';\n" + " input = builder.firstChild;\n" + " alert(input.value + '-' + input.defaultValue + '-' + input.getAttribute('value'));\n" + " }\n" + "</script>\n" + "</head><body onload='test()'>\n" + "<form>\n" + " <input type='number' id='text1'>\n" + "</form>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if the test fails */ @Test @Alerts({"--null", "--null", "--null"}) public void defaultValuesAfterClone() throws Exception { final String html = "<html><head><title>foo</title>\n" + "<script>\n" + " function test() {\n" + " var input = document.getElementById('text1');\n" + " input = input.cloneNode(false);\n" + " alert(input.value + '-' + input.defaultValue + '-' + input.getAttribute('value'));\n" + " input = document.createElement('input');\n" + " input.type = 'number';\n" + " input = input.cloneNode(false);\n" + " alert(input.value + '-' + input.defaultValue + '-' + input.getAttribute('value'));\n" + " var builder = document.createElement('div');\n" + " builder.innerHTML = '<input type=\"text\">';\n" + " input = builder.firstChild;\n" + " input = input.cloneNode(false);\n" + " alert(input.value + '-' + input.defaultValue + '-' + input.getAttribute('value'));\n" + " }\n" + "</script>\n" + "</head><body onload='test()'>\n" + "<form>\n" + " <input type='number' id='text1'>\n" + "</form>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if the test fails */ @Test @Alerts({"1234-1234-1234", "1234-1234-1234", "5678-1234-1234", "5678-1234-1234", "5678-2345-2345", "5678-2345-2345"}) @NotYetImplemented public void resetByClick() throws Exception { final String html = "<html><head><title>foo</title>\n" + "<script>\n" + " function test() {\n" + " var text = document.getElementById('testId');\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " document.getElementById('testReset').click;\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " text.value = '5678';\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " document.getElementById('testReset').click;\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " text.defaultValue = '2345';\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " document.forms[0].reset;\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " }\n" + "</script>\n" + "</head><body onload='test()'>\n" + "<form>\n" + " <input type='number' id='testId' value='1234'>\n" + " <input type='reset' id='testReset'>\n" + "</form>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if the test fails */ @Test @Alerts({"1234-1234-1234", "1234-1234-1234", "5678-1234-1234", "5678-1234-1234", "5678-2345-2345", "5678-2345-2345"}) @NotYetImplemented public void resetByJS() throws Exception { final String html = "<html><head><title>foo</title>\n" + "<script>\n" + " function test() {\n" + " var text = document.getElementById('testId');\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " document.forms[0].reset;\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " text.value = '5678';\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " document.forms[0].reset;\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " text.defaultValue = '2345';\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " document.forms[0].reset;\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " }\n" + "</script>\n" + "</head><body onload='test()'>\n" + "<form>\n" + " <input type='number' id='testId' value='1234'>\n" + "</form>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if the test fails */ @Test @Alerts({"1234-1234-1234", "2345-2345-2345", "3456-2345-2345", "3456-9876-9876", "3456-44-44"}) @NotYetImplemented public void value() throws Exception { final String html = "<html><head><title>foo</title>\n" + "<script>\n" + " function test() {\n" + " var text = document.getElementById('testId');\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " text.defaultValue = '2345';\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " text.value = '3456';\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " text.setAttribute('value', '9876');\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " text.defaultValue = '44';\n" + " alert(text.value + '-' + text.defaultValue + '-' + text.getAttribute('value'));\n" + " }\n" + "</script>\n" + "</head><body onload='test()'>\n" + "<form>\n" + " <input type='number' id='testId' value='1234'>\n" + "</form>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = {"textLength not available"}, FF = {"7"}) public void textLength() throws Exception { final String html = "<html><head><title>foo</title>\n" + "<script>\n" + " function test() {\n" + " var text = document.getElementById('testId');\n" + " if(text.textLength) {\n" + " alert(text.textLength);\n" + " } else {\n" + " alert('textLength not available');\n" + " }\n" + " }\n" + "</script>\n" + "</head><body onload='test()'>\n" + "<form>\n" + " <input type='number' id='testId' value='1234567'>\n" + "</form>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if an error occurs */ @Test @Alerts(DEFAULT = "0", CHROME = "exception") @NotYetImplemented(CHROME) public void selection() throws Exception { final String html = "<html><head>\n" + "<script>\n" + " function test() {\n" + " alert(getSelection(document.getElementById('text1')).length);\n" + " }\n" + " function getSelection(element) {\n" + " if (!('selectionStart' in element)) { alert('no selectionStart'); }\n" + " if (!('selectionEnd' in element)) { alert('no selectionEnd'); }\n" + " try {\n" + " return element.value.substring(element.selectionStart, element.selectionEnd);\n" + " } catch(e) { alert('exception'); }\n" + " }\n" + "</script></head>\n" + "<body onload='test()'>\n" + " <input type='number' id='text1'/>\n" + "</body></html>"; loadPageWithAlerts2(html); } /** * @throws Exception if test fails */ @Test @Alerts(DEFAULT = {"0,0", "11,11", "3,11", "3,10"}, CHROME = {"exception", "exception", "exception", "exception", "exception", "exception"}, IE = {"0,0", "0,0", "3,3", "3,10"}) public void selection2_1() throws Exception { selection2(3, 10); } /** * @throws Exception if test fails */ @Test @Alerts(DEFAULT = {"0,0", "11,11", "0,11", "0,11"}, CHROME = {"exception", "exception", "exception", "exception", "exception", "exception"}, IE = {"0,0", "0,0", "0,0", "0,11"}) public void selection2_2() throws Exception { selection2(-3, 15); } /** * @throws Exception if test fails */ @Test @Alerts(DEFAULT = {"0,0", "11,11", "10,11", "5,5"}, CHROME = {"exception", "exception", "exception", "exception", "exception", "exception"}, IE = {"0,0", "0,0", "10,10", "5,5"}) public void selection2_3() throws Exception { selection2(10, 5); } private void selection2(final int selectionStart, final int selectionEnd) throws Exception { final String html = "<html>\n" + "<body>\n" + "<input id='myTextInput' value='1234567' type='number'>\n" + "<script>\n" + " var input = document.getElementById('myTextInput');\n" + " if (!('selectionStart' in input)) { alert('no selectionStart'); }\n" + " if (!('selectionEnd' in input)) { alert('no selectionEnd'); }\n" + " try {\n" + " alert(input.selectionStart + ',' + input.selectionEnd);\n" + " } catch(e) { alert('exception'); }\n" + " input.value = '12345678900';\n" + " try {\n" + " alert(input.selectionStart + ',' + input.selectionEnd);\n" + " } catch(e) { alert('exception'); }\n" + " try {\n" + " input.selectionStart = " + selectionStart + ";\n" + " } catch(e) { alert('exception'); }\n" + " try {\n" + " alert(input.selectionStart + ',' + input.selectionEnd);\n" + " } catch(e) { alert('exception'); }\n" + " try {\n" + " input.selectionEnd = " + selectionEnd + ";\n" + " } catch(e) { alert('exception'); }\n" + " try {\n" + " alert(input.selectionStart + ',' + input.selectionEnd);\n" + " } catch(e) { alert('exception'); }\n" + "</script>\n" + "</body>\n" + "</html>"; loadPageWithAlerts2(html); } /** * @throws Exception if test fails */ @Test @Alerts(DEFAULT = {"0,0", "4,5", "10,10", "4,4", "1,1"}, CHROME = "exception", IE = {"0,0", "4,5", "0,0", "0,0", "0,0"}) public void selectionOnUpdate() throws Exception { final String html = "<html>\n" + "<body>\n" + "<input id='myTextInput' value='1234567' type='number'>\n" + "<script>\n" + " var input = document.getElementById('myTextInput');\n" + " if (!('selectionStart' in input)) { alert('no selectionStart'); }\n" + " if (!('selectionEnd' in input)) { alert('no selectionEnd'); }\n" + " try {\n" + " alert(input.selectionStart + ',' + input.selectionEnd);\n" + " input.selectionStart = 4;\n" + " input.selectionEnd = 5;\n" + " alert(input.selectionStart + ',' + input.selectionEnd);\n" + " input.value = '1234567890';\n" + " alert(input.selectionStart + ',' + input.selectionEnd);\n" + " input.value = '9876';\n" + " alert(input.selectionStart + ',' + input.selectionEnd);\n" + " input.selectionStart = 0;\n" + " input.selectionEnd = 4;\n" + " input.value = '7';\n" + " alert(input.selectionStart + ',' + input.selectionEnd);\n" + " } catch(e) { alert('exception'); }\n" + "</script>\n" + "</body>\n" + "</html>"; loadPageWithAlerts2(html); } /** * @throws Exception if the test fails */ @Test public void submitOnEnter() throws Exception { final String html = "<html>\n" + "<body>\n" + " <form action='result.html'>\n" + " <input id='t' value='1234'/>\n" + " </form>\n" + "</body>\n" + "</html>"; final WebDriver driver = loadPage2(html); final WebElement field = driver.findElement(By.id("t")); field.sendKeys("\n"); assertEquals(2, getMockWebConnection().getRequestCount()); } /** * @throws Exception if the test fails */ @Test @NotYetImplemented public void submitOnEnterWithoutForm() throws Exception { // this seem to be a bug in Selenium // real browsers simply ignore the missing form final String html = "<html>\n" + "<body>\n" + " <input id='t' value='1234'/>\n" + "</body>\n" + "</html>"; final WebDriver driver = loadPage2(html); final WebElement field = driver.findElement(By.id("t")); field.sendKeys("\n"); assertEquals(1, getMockWebConnection().getRequestCount()); } }
package com.study.component.bean; import com.study.component.DespositMode; import org.springframework.core.annotation.Order; /** * 类说明: * * <pre> * Modify Information: * Author Date Description * ============ ============= ============================ * VilderLee 2019/4/12 Create this file * </pre> */ @DespositMode(mode = 10)@Order(1) public class Tx1005 extends AbstractTx1{ @Override protected void tx1002() { System.out.println("This is Tx1005 !!!"); } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. /** * ProductActionError.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.admanager.axis.v201805; /** * Lists all error reasons associated with performing actions on {@link * Product products}. */ public class ProductActionError extends com.google.api.ads.admanager.axis.v201805.ApiError implements java.io.Serializable { /* The error reason represented by an enum. */ private com.google.api.ads.admanager.axis.v201805.ProductActionErrorReason reason; public ProductActionError() { } public ProductActionError( java.lang.String fieldPath, com.google.api.ads.admanager.axis.v201805.FieldPathElement[] fieldPathElements, java.lang.String trigger, java.lang.String errorString, com.google.api.ads.admanager.axis.v201805.ProductActionErrorReason reason) { super( fieldPath, fieldPathElements, trigger, errorString); this.reason = reason; } @Override public String toString() { return com.google.common.base.MoreObjects.toStringHelper(this.getClass()) .omitNullValues() .add("errorString", getErrorString()) .add("fieldPath", getFieldPath()) .add("fieldPathElements", getFieldPathElements()) .add("reason", getReason()) .add("trigger", getTrigger()) .toString(); } /** * Gets the reason value for this ProductActionError. * * @return reason * The error reason represented by an enum. */ public com.google.api.ads.admanager.axis.v201805.ProductActionErrorReason getReason() { return reason; } /** * Sets the reason value for this ProductActionError. * * @param reason * The error reason represented by an enum. */ public void setReason(com.google.api.ads.admanager.axis.v201805.ProductActionErrorReason reason) { this.reason = reason; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof ProductActionError)) return false; ProductActionError other = (ProductActionError) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.reason==null && other.getReason()==null) || (this.reason!=null && this.reason.equals(other.getReason()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getReason() != null) { _hashCode += getReason().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(ProductActionError.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201805", "ProductActionError")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("reason"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201805", "reason")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201805", "ProductActionError.Reason")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
package blog.javamagic.pfp.filter; public interface LineFilter { boolean f( String[] line ); }
/****************************************************************************** * Compilation: javac StdRandom.java * Execution: java StdRandom * Dependencies: StdOut.java * * A library of static methods to generate pseudo-random numbers from * different distributions (bernoulli, uniform, gaussian, discrete, * and exponential). Also includes a method for shuffling an array. * * * % java StdRandom 5 * seed = 1316600602069 * 59 16.81826 true 8.83954 0 * 32 91.32098 true 9.11026 0 * 35 10.11874 true 8.95396 3 * 92 32.88401 true 8.87089 0 * 72 92.55791 true 9.46241 0 * * % java StdRandom 5 * seed = 1316600616575 * 96 60.17070 true 8.72821 0 * 79 32.01607 true 8.58159 0 * 81 59.49065 true 9.10423 1 * 96 51.65818 true 9.02102 0 * 99 17.55771 true 8.99762 0 * * % java StdRandom 5 1316600616575 * seed = 1316600616575 * 96 60.17070 true 8.72821 0 * 79 32.01607 true 8.58159 0 * 81 59.49065 true 9.10423 1 * 96 51.65818 true 9.02102 0 * 99 17.55771 true 8.99762 0 * * * Remark * ------ * - Relies on randomness of nextDouble() method in java.util.Random * to generate pseudorandom numbers in [0, 1). * * - This library allows you to set and get the pseudorandom number seed. * * - See http://www.honeylocust.com/RngPack/ for an industrial * strength random number generator in Java. * ******************************************************************************/ import java.util.Random; /** * The {@code StdRandom} class provides static methods for generating * random number from various discrete and continuous distributions, * including Bernoulli, uniform, Gaussian, exponential, pareto, * Poisson, and Cauchy. It also provides method for shuffling an * array or subarray. * <p> * For additional documentation, * see <a href="http://introcs.cs.princeton.edu/22library">Section 2.2</a> of * <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> * by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public final class StdRandom { private static Random random; // pseudo-random number generator private static long seed; // pseudo-random number generator seed // static initializer static { // this is how the seed was set in Java 1.4 seed = System.currentTimeMillis(); random = new Random(seed); } // don't instantiate private StdRandom() { } /** * Sets the seed of the pseudorandom number generator. * This method enables you to produce the same sequence of "random" * number for each execution of the program. * Ordinarily, you should call this method at most once per program. * * @param s the seed */ public static void setSeed(long s) { seed = s; random = new Random(seed); } /** * Returns the seed of the pseudorandom number generator. * * @return the seed */ public static long getSeed() { return seed; } /** * Returns a random real number uniformly in [0, 1). * * @return a random real number uniformly in [0, 1) */ public static double uniform() { return random.nextDouble(); } /** * Returns a random integer uniformly in [0, n). * * @param n number of possible integers * @return a random integer uniformly between 0 (inclusive) and <tt>N</tt> (exclusive) * @throws IllegalArgumentException if <tt>n <= 0</tt> */ public static int uniform(int n) { if (n <= 0) throw new IllegalArgumentException("Parameter N must be positive"); return random.nextInt(n); } /////////////////////////////////////////////////////////////////////////// // STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA // THE STATIC METHODS ABOVE. /////////////////////////////////////////////////////////////////////////// /** * Returns a random real number uniformly in [0, 1). * * @return a random real number uniformly in [0, 1) * @deprecated Replaced by {@link #uniform()}. */ public static double random() { return uniform(); } /** * Returns a random integer uniformly in [a, b). * * @param a the left endpoint * @param b the right endpoint * @return a random integer uniformly in [a, b) * @throws IllegalArgumentException if <tt>b <= a</tt> * @throws IllegalArgumentException if <tt>b - a >= Integer.MAX_VALUE</tt> */ public static int uniform(int a, int b) { if (b <= a) throw new IllegalArgumentException("Invalid range"); if ((long) b - a >= Integer.MAX_VALUE) throw new IllegalArgumentException("Invalid range"); return a + uniform(b - a); } /** * Returns a random real number uniformly in [a, b). * * @param a the left endpoint * @param b the right endpoint * @return a random real number uniformly in [a, b) * @throws IllegalArgumentException unless <tt>a < b</tt> */ public static double uniform(double a, double b) { if (!(a < b)) throw new IllegalArgumentException("Invalid range"); return a + uniform() * (b-a); } /** * Returns a random boolean from a Bernoulli distribution with success * probability <em>p</em>. * * @param p the probability of returning <tt>true</tt> * @return <tt>true</tt> with probability <tt>p</tt> and * <tt>false</tt> with probability <tt>p</tt> * @throws IllegalArgumentException unless <tt>p >= 0.0</tt> and <tt>p <= 1.0</tt> */ public static boolean bernoulli(double p) { if (!(p >= 0.0 && p <= 1.0)) throw new IllegalArgumentException("Probability must be between 0.0 and 1.0"); return uniform() < p; } /** * Returns a random boolean from a Bernoulli distribution with success * probability 1/2. * * @return <tt>true</tt> with probability 1/2 and * <tt>false</tt> with probability 1/2 */ public static boolean bernoulli() { return bernoulli(0.5); } /** * Returns a random real number from a standard Gaussian distribution. * * @return a random real number from a standard Gaussian distribution * (mean 0 and standard deviation 1). */ public static double gaussian() { // use the polar form of the Box-Muller transform double r, x, y; do { x = uniform(-1.0, 1.0); y = uniform(-1.0, 1.0); r = x*x + y*y; } while (r >= 1 || r == 0); return x * Math.sqrt(-2 * Math.log(r) / r); // Remark: y * Math.sqrt(-2 * Math.log(r) / r) // is an independent random gaussian } /** * Returns a random real number from a Gaussian distribution with mean &mu; * and standard deviation &sigma;. * * @param mu the mean * @param sigma the standard deviation * @return a real number distributed according to the Gaussian distribution * with mean <tt>mu</tt> and standard deviation <tt>sigma</tt> */ public static double gaussian(double mu, double sigma) { return mu + sigma * gaussian(); } /** * Returns a random integer from a geometric distribution with success * probability <em>p</em>. * * @param p the parameter of the geometric distribution * @return a random integer from a geometric distribution with success * probability <tt>p</tt> * @throws IllegalArgumentException unless <tt>p >= 0.0</tt> and <tt>p <= 1.0</tt> */ public static int geometric(double p) { if (!(p >= 0.0 && p <= 1.0)) throw new IllegalArgumentException("Probability must be between 0.0 and 1.0"); // using algorithm given by Knuth return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p)); } /** * Returns a random integer from a Poisson distribution with mean &lambda;. * * @param lambda the mean of the Poisson distribution * @return a random integer from a Poisson distribution with mean <tt>lambda</tt> * @throws IllegalArgumentException unless <tt>lambda > 0.0</tt> and not infinite */ public static int poisson(double lambda) { if (!(lambda > 0.0)) throw new IllegalArgumentException("Parameter lambda must be positive"); if (Double.isInfinite(lambda)) throw new IllegalArgumentException("Parameter lambda must not be infinite"); // using algorithm given by Knuth // see http://en.wikipedia.org/wiki/Poisson_distribution int k = 0; double p = 1.0; double L = Math.exp(-lambda); do { k++; p *= uniform(); } while (p >= L); return k-1; } /** * Returns a random real number from the standard Pareto distribution. * * @return a random real number from the standard Pareto distribution */ public static double pareto() { return pareto(1.0); } /** * Returns a random real number from a Pareto distribution with * shape parameter &alpha;. * * @param alpha shape parameter * @return a random real number from a Pareto distribution with shape * parameter <tt>alpha</tt> * @throws IllegalArgumentException unless <tt>alpha > 0.0</tt> */ public static double pareto(double alpha) { if (!(alpha > 0.0)) throw new IllegalArgumentException("Shape parameter alpha must be positive"); return Math.pow(1 - uniform(), -1.0/alpha) - 1.0; } /** * Returns a random real number from the Cauchy distribution. * * @return a random real number from the Cauchy distribution. */ public static double cauchy() { return Math.tan(Math.PI * (uniform() - 0.5)); } /** * Returns a random integer from the specified discrete distribution. * * @param probabilities the probability of occurrence of each integer * @return a random integer from a discrete distribution: * <tt>i</tt> with probability <tt>probabilities[i]</tt> * @throws NullPointerException if <tt>probabilities</tt> is <tt>null</tt> * @throws IllegalArgumentException if sum of array entries is not (very nearly) equal to <tt>1.0</tt> * @throws IllegalArgumentException unless <tt>probabilities[i] >= 0.0</tt> for each index <tt>i</tt> */ public static int discrete(double[] probabilities) { if (probabilities == null) throw new NullPointerException("argument array is null"); double EPSILON = 1E-14; double sum = 0.0; for (int i = 0; i < probabilities.length; i++) { if (!(probabilities[i] >= 0.0)) throw new IllegalArgumentException("array entry " + i + " must be nonnegative: " + probabilities[i]); sum += probabilities[i]; } if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON) throw new IllegalArgumentException("sum of array entries does not approximately equal 1.0: " + sum); // the for loop may not return a value when both r is (nearly) 1.0 and when the // cumulative sum is less than 1.0 (as a result of floating-point roundoff error) while (true) { double r = uniform(); sum = 0.0; for (int i = 0; i < probabilities.length; i++) { sum = sum + probabilities[i]; if (sum > r) return i; } } } /** * Returns a random integer from the specified discrete distribution. * * @param frequencies the frequency of occurrence of each integer * @return a random integer from a discrete distribution: * <tt>i</tt> with probability proportional to <tt>frequencies[i]</tt> * @throws NullPointerException if <tt>frequencies</tt> is <tt>null</tt> * @throws IllegalArgumentException if all array entries are <tt>0</tt> * @throws IllegalArgumentException if <tt>frequencies[i]</tt> is negative for any index <tt>i</tt> * @throws IllegalArgumentException if sum of frequencies exceeds <tt>Integer.MAX_VALUE</tt> (2<sup>31</sup> - 1) */ public static int discrete(int[] frequencies) { if (frequencies == null) throw new NullPointerException("argument array is null"); long sum = 0; for (int i = 0; i < frequencies.length; i++) { if (frequencies[i] < 0) throw new IllegalArgumentException("array entry " + i + " must be nonnegative: " + frequencies[i]); sum += frequencies[i]; } if (sum == 0) throw new IllegalArgumentException("at least one array entry must be positive"); if (sum >= Integer.MAX_VALUE) throw new IllegalArgumentException("sum of frequencies overflows an int"); // pick index i with probabilitity proportional to frequency double r = uniform((int) sum); sum = 0; for (int i = 0; i < frequencies.length; i++) { sum += frequencies[i]; if (sum > r) return i; } // can't reach here assert false; return -1; } /** * Returns a random real number from an exponential distribution * with rate &lambda;. * * @param lambda the rate of the exponential distribution * @return a random real number from an exponential distribution with * rate <tt>lambda</tt> * @throws IllegalArgumentException unless <tt>lambda > 0.0</tt> */ public static double exp(double lambda) { if (!(lambda > 0.0)) throw new IllegalArgumentException("Rate lambda must be positive"); return -Math.log(1 - uniform()) / lambda; } /** * Rearranges the elements of the specified array in uniformly random order. * * @param a the array to shuffle * @throws NullPointerException if <tt>a</tt> is <tt>null</tt> */ public static void shuffle(Object[] a) { if (a == null) throw new NullPointerException("argument array is null"); int n = a.length; for (int i = 0; i < n; i++) { int r = i + uniform(n-i); // between i and n-1 Object temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified array in uniformly random order. * * @param a the array to shuffle * @throws NullPointerException if <tt>a</tt> is <tt>null</tt> */ public static void shuffle(double[] a) { if (a == null) throw new NullPointerException("argument array is null"); int n = a.length; for (int i = 0; i < n; i++) { int r = i + uniform(n-i); // between i and n-1 double temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified array in uniformly random order. * * @param a the array to shuffle * @throws NullPointerException if <tt>a</tt> is <tt>null</tt> */ public static void shuffle(int[] a) { if (a == null) throw new NullPointerException("argument array is null"); int n = a.length; for (int i = 0; i < n; i++) { int r = i + uniform(n-i); // between i and n-1 int temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified subarray in uniformly random order. * * @param a the array to shuffle * @param lo the left endpoint (inclusive) * @param hi the right endpoint (inclusive) * @throws NullPointerException if <tt>a</tt> is <tt>null</tt> * @throws IndexOutOfBoundsException unless <tt>(0 <= lo) && (lo <= hi) && (hi < a.length)</tt> * */ public static void shuffle(Object[] a, int lo, int hi) { if (a == null) throw new NullPointerException("argument array is null"); if (lo < 0 || lo > hi || hi >= a.length) { throw new IndexOutOfBoundsException("Illegal subarray range"); } for (int i = lo; i <= hi; i++) { int r = i + uniform(hi-i+1); // between i and hi Object temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified subarray in uniformly random order. * * @param a the array to shuffle * @param lo the left endpoint (inclusive) * @param hi the right endpoint (inclusive) * @throws NullPointerException if <tt>a</tt> is <tt>null</tt> * @throws IndexOutOfBoundsException unless <tt>(0 <= lo) && (lo <= hi) && (hi < a.length)</tt> */ public static void shuffle(double[] a, int lo, int hi) { if (a == null) throw new NullPointerException("argument array is null"); if (lo < 0 || lo > hi || hi >= a.length) { throw new IndexOutOfBoundsException("Illegal subarray range"); } for (int i = lo; i <= hi; i++) { int r = i + uniform(hi-i+1); // between i and hi double temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Rearranges the elements of the specified subarray in uniformly random order. * * @param a the array to shuffle * @param lo the left endpoint (inclusive) * @param hi the right endpoint (inclusive) * @throws NullPointerException if <tt>a</tt> is <tt>null</tt> * @throws IndexOutOfBoundsException unless <tt>(0 <= lo) && (lo <= hi) && (hi < a.length)</tt> */ public static void shuffle(int[] a, int lo, int hi) { if (a == null) throw new NullPointerException("argument array is null"); if (lo < 0 || lo > hi || hi >= a.length) { throw new IndexOutOfBoundsException("Illegal subarray range"); } for (int i = lo; i <= hi; i++) { int r = i + uniform(hi-i+1); // between i and hi int temp = a[i]; a[i] = a[r]; a[r] = temp; } } /** * Unit test. */ public static void main(String[] args) { int n = Integer.parseInt(args[0]); if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1])); double[] probabilities = { 0.5, 0.3, 0.1, 0.1 }; int[] frequencies = { 5, 3, 1, 1 }; String[] a = "A B C D E F G".split(" "); StdOut.println("seed = " + StdRandom.getSeed()); for (int i = 0; i < n; i++) { StdOut.printf("%2d " , uniform(100)); StdOut.printf("%8.5f ", uniform(10.0, 99.0)); StdOut.printf("%5b " , bernoulli(0.5)); StdOut.printf("%7.5f ", gaussian(9.0, 0.2)); StdOut.printf("%1d " , discrete(probabilities)); StdOut.printf("%1d " , discrete(frequencies)); StdRandom.shuffle(a); for (String s : a) StdOut.print(s); StdOut.println(); } } }
/* * Copyright (c) OSGi Alliance (2010, 2013). 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. */ /** * Framework Bundle Hooks Package Version 1.1. * * <p> * Bundles wishing to use this package must list the package in the * Import-Package header of the bundle's manifest. * * <p> * Example import for consumers using the API in this package: * <p> * {@code Import-Package: org.osgi.framework.hooks.bundle; version="[1.1,2.0)"} * * @author $Id: package-info.java 1614569 2014-07-30 07:22:32Z cziegeler $ */ @Version("1.1") package org.osgi.framework.hooks.bundle; import org.osgi.annotation.versioning.Version;
/* * BridJ - Dynamic and blazing-fast native interop for Java. * http://bridj.googlecode.com/ * * Copyright (c) 2010-2015, Olivier Chafik (http://ochafik.com/) * 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 Olivier Chafik 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 OLIVIER CHAFIK 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 REGENTS AND 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.bridj.objc; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Selector { String value(); }
package edu.fiuba.algo3.loaders; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.fiuba.algo3.constants.ResourceConstants; import edu.fiuba.algo3.exceptions.QuestionsNotLoadedException; import edu.fiuba.algo3.model.Game; import edu.fiuba.algo3.model.Player; public class GameLoader { private GameLoader() {} private static final Logger logger = LoggerFactory.getLogger(GameLoader.class); public static Game loadGame(List<Player> players) { try { return new Game(players, QuestionLoader.loadQuestions(ResourceConstants.QUESTIONS_PATH)); } catch (QuestionsNotLoadedException ex) { logger.error("Question not loaded", ex); SceneLoader.loadErrorPage(); } return null; } }
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at: * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package software.amazon.ion.impl.lite; import software.amazon.ion.IonContainer; import software.amazon.ion.SymbolTable; /** * Provides the parent, system and symbol table definitions that are shared * by one or more hierarchies of IonValues. * <p> * The type of context used by a value depends on its position. * <ul> * <li>Top-level values have either a {@link TopLevelContext} or an * {@link IonSystemLite} for a context. * <li>Non-top-level values have their {@link IonContainer} for a context. * <li>Datagrams have their {@link IonSystemLite} for a context. * </ul> * <p> * Concrete * contexts simply return the correct values (and * own them). Containers return themselves as the * parent and delegate to their parent for the * system and symbol table values. Note that values * contained directly by a datagram may store a * symbol table locally as there may be more than * one symbol table in a datagram. */ interface IonContext { /** * Return the container of values associated with this context. * If this context is an {@link IonContainerLite} it returns itself. * * @return the container of the value; * null for stand-alone top level values. */ abstract IonContainerLite getContextContainer(); /** * Get the IonSystem concrete object that created * the IonValue that is associated with this context. * Generally this delegates to the parent. * * @return not null */ abstract IonSystemLite getSystem(); /** * Returns the symbol table that is directly assigned to this context. * For {@link TopLevelContext} it is the symbol table member. * For {@link IonContainerLite} and {@link IonSystemLite} it is null. * * @return the directly assigned symbol table, with no recursive lookup. */ abstract SymbolTable getContextSymbolTable(); }
/* * Copyright (c) 2021 CMCORP * * 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. * An intermediate form of license used by the X Consortium for X11 used the following wording:[16] * */ package com.cmcorp.spring.BibliotecaDelDesierto.model.dto; import com.cmcorp.spring.BibliotecaDelDesierto.model.Libro; import org.springframework.web.multipart.MultipartFile; import java.util.List; /** * Class LibroCategoriaDTO */ public class LibroCategoriaDTO { /** * Entity Libro */ private Libro libro; /** * Integer id Idioma */ private Integer idioma_id; /** * List of categories */ private List<Integer> listaCategorias; private MultipartFile imagen; private MultipartFile archivoPdf; /** * Constructor */ public LibroCategoriaDTO(){ } /** * Constructor with params * @param libro * @param idioma_id * @param listaCategorias */ public LibroCategoriaDTO(Libro libro, Integer idioma_id, List<Integer> listaCategorias) { this.libro = libro; this.idioma_id = idioma_id; this.listaCategorias = listaCategorias; } public Libro getLibro() { return libro; } public Integer getIdioma_id() { return idioma_id; } public List<Integer> getListaCategorias() { return listaCategorias; } public void setLibro(Libro libro) { this.libro = libro; } public void setIdioma_id(Integer idioma_id) { this.idioma_id = idioma_id; } public void setListaCategorias(List<Integer> listaCategorias) { this.listaCategorias = listaCategorias; } public MultipartFile getImagen() { return imagen; } public void setImagen(MultipartFile imagen) { this.imagen = imagen; } public MultipartFile getArchivoPdf() { return archivoPdf; } public void setArchivoPdf(MultipartFile archivoPdf) { this.archivoPdf = archivoPdf; } }
/* * 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 compressionFilters; import java.io.IOException; import java.io.OutputStream; import java.util.zip.GZIPOutputStream; import javax.servlet.ServletOutputStream; /** * Implementation of <b>ServletOutputStream</b> that works with * the CompressionServletResponseWrapper implementation. * * @author Amy Roh * @author Dmitri Valdin */ public class CompressionResponseStream extends ServletOutputStream { // ----------------------------------------------------------- Constructors /** * Construct a servlet output stream associated with the specified Response. * * @param responseWrapper The associated response wrapper * @param originalOutput the output stream */ public CompressionResponseStream( CompressionServletResponseWrapper responseWrapper, ServletOutputStream originalOutput) { super(); closed = false; this.response = responseWrapper; this.output = originalOutput; } // ----------------------------------------------------- Instance Variables /** * The threshold number which decides to compress or not. * Users can configure in web.xml to set it to fit their needs. */ protected int compressionThreshold = 0; /** * The compression buffer size to avoid chunking */ protected int compressionBuffer = 0; /** * The mime types to compress */ protected String[] compressionMimeTypes = {"text/html", "text/xml", "text/plain"}; /** * Debug level */ private int debug = 0; /** * The buffer through which all of our output bytes are passed. */ protected byte[] buffer = null; /** * The number of data bytes currently in the buffer. */ protected int bufferCount = 0; /** * The underlying gzip output stream to which we should write data. */ protected OutputStream gzipstream = null; /** * Has this stream been closed? */ protected boolean closed = false; /** * The content length past which we will not write, or -1 if there is * no defined content length. */ protected int length = -1; /** * The response with which this servlet output stream is associated. */ protected CompressionServletResponseWrapper response = null; /** * The underlying servlet output stream to which we should write data. */ protected ServletOutputStream output = null; // --------------------------------------------------------- Public Methods /** * Set debug level */ public void setDebugLevel(int debug) { this.debug = debug; } /** * Set the compressionThreshold number and create buffer for this size */ protected void setCompressionThreshold(int compressionThreshold) { this.compressionThreshold = compressionThreshold; buffer = new byte[this.compressionThreshold]; if (debug > 1) { System.out.println("compressionThreshold is set to "+ this.compressionThreshold); } } /** * The compression buffer size to avoid chunking */ protected void setCompressionBuffer(int compressionBuffer) { this.compressionBuffer = compressionBuffer; if (debug > 1) { System.out.println("compressionBuffer is set to "+ this.compressionBuffer); } } /** * Set supported mime types */ public void setCompressionMimeTypes(String[] compressionMimeTypes) { this.compressionMimeTypes = compressionMimeTypes; if (debug > 1) { System.out.println("compressionMimeTypes is set to " + this.compressionMimeTypes); } } /** * Close this output stream, causing any buffered data to be flushed and * any further output data to throw an IOException. */ @Override public void close() throws IOException { if (debug > 1) { System.out.println("close() @ CompressionResponseStream"); } if (closed) throw new IOException("This output stream has already been closed"); if (gzipstream != null) { flushToGZip(); gzipstream.close(); gzipstream = null; } else { if (bufferCount > 0) { if (debug > 2) { System.out.print("output.write("); System.out.write(buffer, 0, bufferCount); System.out.println(")"); } output.write(buffer, 0, bufferCount); bufferCount = 0; } } output.close(); closed = true; } /** * Flush any buffered data for this output stream, which also causes the * response to be committed. */ @Override public void flush() throws IOException { if (debug > 1) { System.out.println("flush() @ CompressionResponseStream"); } if (closed) { throw new IOException("Cannot flush a closed output stream"); } if (gzipstream != null) { gzipstream.flush(); } } public void flushToGZip() throws IOException { if (debug > 1) { System.out.println("flushToGZip() @ CompressionResponseStream"); } if (bufferCount > 0) { if (debug > 1) { System.out.println("flushing out to GZipStream, bufferCount = " + bufferCount); } writeToGZip(buffer, 0, bufferCount); bufferCount = 0; } } /** * Write the specified byte to our output stream. * * @param b The byte to be written * * @exception IOException if an input/output error occurs */ @Override public void write(int b) throws IOException { if (debug > 1) { System.out.println("write "+b+" in CompressionResponseStream "); } if (closed) throw new IOException("Cannot write to a closed output stream"); if (bufferCount >= buffer.length) { flushToGZip(); } buffer[bufferCount++] = (byte) b; } /** * Write <code>b.length</code> bytes from the specified byte array * to our output stream. * * @param b The byte array to be written * * @exception IOException if an input/output error occurs */ @Override public void write(byte b[]) throws IOException { write(b, 0, b.length); } /** * Write <code>len</code> bytes from the specified byte array, starting * at the specified offset, to our output stream. * * @param b The byte array containing the bytes to be written * @param off Zero-relative starting offset of the bytes to be written * @param len The number of bytes to be written * * @exception IOException if an input/output error occurs */ @Override public void write(byte b[], int off, int len) throws IOException { if (debug > 1) { System.out.println("write, bufferCount = " + bufferCount + " len = " + len + " off = " + off); } if (debug > 2) { System.out.print("write("); System.out.write(b, off, len); System.out.println(")"); } if (closed) throw new IOException("Cannot write to a closed output stream"); if (len == 0) return; // Can we write into buffer ? if (len <= (buffer.length - bufferCount)) { System.arraycopy(b, off, buffer, bufferCount, len); bufferCount += len; return; } // There is not enough space in buffer. Flush it ... flushToGZip(); // ... and try again. Note, that bufferCount = 0 here ! if (len <= (buffer.length - bufferCount)) { System.arraycopy(b, off, buffer, bufferCount, len); bufferCount += len; return; } // write direct to gzip writeToGZip(b, off, len); } public void writeToGZip(byte b[], int off, int len) throws IOException { if (debug > 1) { System.out.println("writeToGZip, len = " + len); } if (debug > 2) { System.out.print("writeToGZip("); System.out.write(b, off, len); System.out.println(")"); } if (gzipstream == null) { if (debug > 1) { System.out.println("new GZIPOutputStream"); } boolean alreadyCompressed = false; String contentEncoding = response.getHeader("Content-Encoding"); if (contentEncoding != null) { if (contentEncoding.contains("gzip")) { alreadyCompressed = true; if (debug > 0) { System.out.println("content is already compressed"); } } else { if (debug > 0) { System.out.println("content is not compressed yet"); } } } boolean compressibleMimeType = false; // Check for compatible MIME-TYPE if (compressionMimeTypes != null) { if (startsWithStringArray(compressionMimeTypes, response.getContentType())) { compressibleMimeType = true; if (debug > 0) { System.out.println("mime type " + response.getContentType() + " is compressible"); } } else { if (debug > 0) { System.out.println("mime type " + response.getContentType() + " is not compressible"); } } } if (response.isCommitted()) { if (debug > 1) System.out.print("Response already committed. Using original output stream"); gzipstream = output; } else if (alreadyCompressed) { if (debug > 1) System.out.print("Response already compressed. Using original output stream"); gzipstream = output; } else if (!compressibleMimeType) { if (debug > 1) System.out.print("Response mime type is not compressible. Using original output stream"); gzipstream = output; } else { response.addHeader("Content-Encoding", "gzip"); response.setContentLength(-1); // don't use any preset content-length as it will be wrong after gzipping response.setBufferSize(compressionBuffer); gzipstream = new GZIPOutputStream(output); } } gzipstream.write(b, off, len); } // -------------------------------------------------------- Package Methods /** * Has this response stream been closed? */ public boolean closed() { return (this.closed); } /** * Checks if any entry in the string array starts with the specified value * * @param sArray the StringArray * @param value string */ private boolean startsWithStringArray(String sArray[], String value) { if (value == null) return false; for (int i = 0; i < sArray.length; i++) { if (value.startsWith(sArray[i])) { return true; } } return false; } }
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2020 DBeaver Corp and others * * 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.jkiss.dbeaver.ext.mssql.model; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.ext.mssql.SQLServerUtils; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.exec.DBCException; import org.jkiss.dbeaver.model.exec.DBCExecutionSource; import org.jkiss.dbeaver.model.exec.DBCSession; import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession; import org.jkiss.dbeaver.model.impl.AbstractExecutionSource; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCStructCache; import org.jkiss.dbeaver.model.impl.jdbc.struct.JDBCTable; import org.jkiss.dbeaver.model.impl.jdbc.struct.JDBCTableColumn; import org.jkiss.dbeaver.model.meta.Association; import org.jkiss.dbeaver.model.meta.Property; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.model.struct.rdb.DBSIndexType; import org.jkiss.dbeaver.model.struct.rdb.DBSManipulationType; import org.jkiss.utils.CommonUtils; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * MySQLTable base */ public abstract class SQLServerTableBase extends JDBCTable<SQLServerDataSource, SQLServerSchema> implements SQLServerObject, DBPNamedObject2, DBPRefreshableObject, DBSObjectWithScript, DBPScriptObjectExt2, DBPSystemObject, DBSDataManipulatorExt { private static final Log log = Log.getLog(SQLServerTableBase.class); private long objectId; private String type; private String description; protected Long rowCount; protected SQLServerTableBase(SQLServerSchema schema) { super(schema, false); } // Copy constructor protected SQLServerTableBase(DBRProgressMonitor monitor, SQLServerSchema catalog, SQLServerTableBase source) throws DBException { super(catalog, source, false); } protected SQLServerTableBase( SQLServerSchema catalog, ResultSet dbResult) { super(catalog, JDBCUtils.safeGetString(dbResult, "name"), true); this.objectId = JDBCUtils.safeGetLong(dbResult, "object_id"); this.description = JDBCUtils.safeGetString(dbResult, "description"); this.type = JDBCUtils.safeGetStringTrimmed(dbResult, "type"); } public SQLServerDatabase getDatabase() { return getSchema().getDatabase(); } public SQLServerSchema getSchema() { return getContainer(); } @Override public JDBCStructCache<SQLServerSchema, ? extends JDBCTable, ? extends JDBCTableColumn> getCache() { return getContainer().getTableCache(); } @Override @Property(viewable = false, editable = false, order = 5) public long getObjectId() { return objectId; } @Property(order = 6) public String getType() { return type; } @Override public boolean isSystem() { return SQLServerObjectType.S.name().equals(type); } @Override @Property(viewable = true, editable = true, updatable = true, multiline = true, order = 100) public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public List<SQLServerTableColumn> getAttributes(@NotNull DBRProgressMonitor monitor) throws DBException { List<SQLServerTableColumn> childColumns = getContainer().getTableCache().getChildren(monitor, getContainer(), this); if (childColumns == null) { return Collections.emptyList(); } List<SQLServerTableColumn> columns = new ArrayList<>(childColumns); columns.sort(DBUtils.orderComparator()); return columns; } @Override public SQLServerTableColumn getAttribute(@NotNull DBRProgressMonitor monitor, @NotNull String attributeName) throws DBException { return getContainer().getTableCache().getChild(monitor, getContainer(), this, attributeName); } public SQLServerTableColumn getAttribute(@NotNull DBRProgressMonitor monitor, @NotNull long columnId) throws DBException { for (SQLServerTableColumn col : getAttributes(monitor)) { if (col.getObjectId() == columnId) { return col; } } log.error("Column '" + columnId + "' not found in table '" + getFullyQualifiedName(DBPEvaluationContext.DML) + "'"); return null; } @Override @Association public Collection<SQLServerTableIndex> getIndexes(DBRProgressMonitor monitor) throws DBException { return this.getContainer().getIndexCache().getObjects(monitor, getSchema(), this); } public SQLServerTableIndex getIndex(DBRProgressMonitor monitor, long indexId) throws DBException { for (SQLServerTableIndex index : getIndexes(monitor)) { if (index.getObjectId() == indexId) { return index; } } log.error("Index '" + indexId + "' not found in table '" + getFullyQualifiedName(DBPEvaluationContext.DML) + "'"); return null; } public SQLServerTableIndex getIndex(DBRProgressMonitor monitor, String name) throws DBException { for (SQLServerTableIndex index : getIndexes(monitor)) { if (CommonUtils.equalObjects(name, index.getName())) { return index; } } log.error("Index '" + name + "' not found in table '" + getFullyQualifiedName(DBPEvaluationContext.DML) + "'"); return null; } @Property(category = CAT_STATISTICS, viewable = false, expensive = true, order = 23) public Long getRowCount(DBRProgressMonitor monitor) throws DBCException { if (rowCount != null || !isPersisted()) { return rowCount; } // Query row count try (DBCSession session = DBUtils.openMetaSession(monitor, this, "Read row count")) { rowCount = countData(new AbstractExecutionSource(this, session.getExecutionContext(), this), session, null, DBSDataContainer.FLAG_NONE); } catch (DBException e) { log.debug("Can't fetch row count", e); } if (rowCount == null) { rowCount = -1L; } return rowCount; } @NotNull @Override public String getFullyQualifiedName(DBPEvaluationContext context) { if (!SQLServerUtils.supportsCrossDatabaseQueries(getDataSource())) { // Older Azure doesn't support database name in queries return DBUtils.getFullQualifiedName(getDataSource(), getSchema(), this); } if (isView() && context == DBPEvaluationContext.DDL) { return DBUtils.getFullQualifiedName(getDataSource(), getSchema(), this); } else { return DBUtils.getFullQualifiedName(getDataSource(), getDatabase(), getSchema(), this); } } //////////////////////////////////////////////////////// // Data manipulation handler @Override public void beforeDataChange(@NotNull DBCSession session, @NotNull DBSManipulationType type, @NotNull DBSAttributeBase[] attributes, @NotNull DBCExecutionSource source) throws DBCException { if (hasIdentInsert(type, attributes)) { enableIdentityInsert(session, true); } } @Override public void afterDataChange(@NotNull DBCSession session, @NotNull DBSManipulationType type, @NotNull DBSAttributeBase[] attributes, @NotNull DBCExecutionSource source) throws DBCException { if (hasIdentInsert(type, attributes)) { enableIdentityInsert(session, false); } } private void enableIdentityInsert(DBCSession session, boolean enable) throws DBCException { try { JDBCUtils.executeStatement( (JDBCSession)session, "SET IDENTITY_INSERT " + getFullyQualifiedName(DBPEvaluationContext.DML) + " " + (enable ? " ON" : "OFF")); } catch (SQLException e) { throw new DBCException(e, session.getExecutionContext()); } } private boolean hasIdentInsert(@NotNull DBSManipulationType type, @NotNull DBSAttributeBase[] attributes) { if (type == DBSManipulationType.INSERT) { for (DBSAttributeBase attr : attributes) { if (attr.isAutoGenerated()) { return true; } } } return false; } @Nullable @Override public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException { rowCount = null; return getContainer().getTableCache().refreshObject(monitor, getContainer(), this); } boolean isClustered(@NotNull DBRProgressMonitor monitor) throws DBException { if (isView()) { return false; } Collection<SQLServerTableIndex> indexes = getIndexes(monitor); if (!CommonUtils.isEmpty(indexes)) { for (SQLServerTableIndex index : indexes) { if (index.getIndexType() == DBSIndexType.CLUSTERED) { return true; } } } return false; } }
package br.com.jabolina.discoveryclient.configuration; import br.com.jabolina.discoveryclient.cluster.IDistributedInstance; import br.com.jabolina.discoveryclient.cluster.impl.atomix.AtomixDistributedInstance; import io.atomix.cluster.Node; import io.atomix.cluster.discovery.BootstrapDiscoveryProvider; import io.atomix.cluster.discovery.NodeDiscoveryProvider; import io.atomix.core.Atomix; import io.atomix.primitive.partition.ManagedPartitionGroup; import io.atomix.protocols.raft.partition.RaftPartitionGroup; import io.atomix.storage.StorageLevel; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import java.io.File; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; @Configuration public class AtomixConfiguration { @Value( "${discovery.address.complete}" ) private String clusterAddr; @Value( "${discovery.atomix.members}" ) private String[] members; @Value( "${discovery.atomix.name}" ) private String name; @Value( "${spring.application.name}" ) private String clusterName; private String diskPath( String posfix ) { return "./cluster/" + name + "/" + UUID.randomUUID().toString() + posfix; } private String memberId( String s ) { return s; // EncDec.encode( s ); } private List< String > clusterMemberIds() { return Arrays.stream( members ) .map( this::memberId ) .collect( Collectors.toList() ); } @Bean public List< Node > clusterMembers() { return Arrays.stream( members ) .map( addr -> Node.builder() .withId( memberId( addr ) ) .withAddress( addr ) .build() ).collect( Collectors.toList() ); } @Bean public NodeDiscoveryProvider membershipProvider() { return BootstrapDiscoveryProvider .builder() .withNodes( clusterMembers() ) .build(); } @Bean public ManagedPartitionGroup managementGroup() { return RaftPartitionGroup .builder( clusterName ) .withDataDirectory( new File( diskPath( "-group" ) ) ) .withNumPartitions( 1 ) .withMembers( clusterMemberIds() ) .build(); } @Bean public ManagedPartitionGroup partitionGroup() { return RaftPartitionGroup .builder( clusterName + "-data" ) .withStorageLevel( StorageLevel.DISK ) .withDataDirectory( new File( diskPath( "-data" ) ) ) .withNumPartitions( 1 ) .withMembers( clusterMemberIds() ) .build(); } @Bean public Atomix atomixInstance() { return Atomix.builder() .withClusterId( clusterName ) .withMemberId( memberId( name ) ) .withAddress( clusterAddr ) .withMembershipProvider( membershipProvider() ) .withManagementGroup( managementGroup() ) .withPartitionGroups( partitionGroup() ) .build(); } @Qualifier( "atomix-distributed-instance" ) @Bean( "atomix-distributed-instance" ) public IDistributedInstance atomixDistributedInstance( Environment environment ) { if ( environment.getProperty( "discovery.distribution.type", "" ).equals( "atomix" ) ) { return new AtomixDistributedInstance( atomixInstance() ); } return null; } }
/* * 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.cassandra.streaming; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.Collection; import java.util.Comparator; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.net.OutboundTcpConnectionPool; import org.apache.cassandra.streaming.messages.StreamInitMessage; import org.apache.cassandra.streaming.messages.StreamMessage; import org.apache.cassandra.utils.FBUtilities; /** * ConnectionHandler manages incoming/outgoing message exchange for the {@link StreamSession}. * * <p> * Internally, ConnectionHandler manages thread to receive incoming {@link StreamMessage} and thread to * send outgoing message. Messages are encoded/decoded on those thread and handed to * {@link StreamSession#messageReceived(org.apache.cassandra.streaming.messages.StreamMessage)}. */ public class ConnectionHandler { private static final Logger logger = LoggerFactory.getLogger(ConnectionHandler.class); private static final int MAX_CONNECT_ATTEMPTS = 3; private final StreamSession session; private IncomingMessageHandler incoming; private OutgoingMessageHandler outgoing; ConnectionHandler(StreamSession session) { this.session = session; } /** * Set up incoming message handler and initiate streaming. * * This method is called once on initiator. * * @throws IOException */ public void initiate() throws IOException { logger.debug("[Stream #{}] Sending stream init for incoming stream", session.planId()); Socket incomingSocket = connect(session.peer); incoming = new IncomingMessageHandler(session, incomingSocket, StreamMessage.CURRENT_VERSION); incoming.sendInitMessage(true); incoming.start(); logger.debug("[Stream #{}] Sending stream init for outgoing stream", session.planId()); Socket outgoingSocket = connect(session.peer); outgoing = new OutgoingMessageHandler(session, outgoingSocket, StreamMessage.CURRENT_VERSION); outgoing.sendInitMessage(false); outgoing.start(); } /** * Set up outgoing message handler on receiving side. * * @param socket socket to use for {@link org.apache.cassandra.streaming.ConnectionHandler.OutgoingMessageHandler}. * @param version Streaming message version * @throws IOException */ public void initiateOnReceivingSide(Socket socket, boolean isForOutgoing, int version) throws IOException { if (isForOutgoing) { outgoing = new OutgoingMessageHandler(session, socket, version); outgoing.start(); } else { incoming = new IncomingMessageHandler(session, socket, version); incoming.start(); } } /** * Connect to peer and start exchanging message. * When connect attempt fails, this retries for maximum of MAX_CONNECT_ATTEMPTS times. * * @param peer the peer to connect to. * @return the created socket. * * @throws IOException when connection failed. */ private static Socket connect(InetAddress peer) throws IOException { int attempts = 0; while (true) { try { Socket socket = OutboundTcpConnectionPool.newSocket(peer); socket.setSoTimeout(DatabaseDescriptor.getStreamingSocketTimeout()); return socket; } catch (IOException e) { if (++attempts >= MAX_CONNECT_ATTEMPTS) throw e; long waitms = DatabaseDescriptor.getRpcTimeout() * (long)Math.pow(2, attempts); logger.warn("Failed attempt {} to connect to {}. Retrying in {} ms. ({})", attempts, peer, waitms, e); try { Thread.sleep(waitms); } catch (InterruptedException wtf) { throw new IOException("interrupted", wtf); } } } } public ListenableFuture<?> close() { logger.debug("[Stream #{}] Closing stream connection handler on {}", session.planId(), session.peer); ListenableFuture<?> inClosed = incoming == null ? Futures.immediateFuture(null) : incoming.close(); ListenableFuture<?> outClosed = outgoing == null ? Futures.immediateFuture(null) : outgoing.close(); return Futures.allAsList(inClosed, outClosed); } /** * Enqueue messages to be sent. * * @param messages messages to send */ public void sendMessages(Collection<? extends StreamMessage> messages) { for (StreamMessage message : messages) sendMessage(message); } public void sendMessage(StreamMessage message) { if (outgoing.isClosed()) throw new RuntimeException("Outgoing stream handler has been closed"); outgoing.enqueue(message); } /** * @return true if outgoing connection is opened and ready to send messages */ public boolean isOutgoingConnected() { return outgoing != null && !outgoing.isClosed(); } abstract static class MessageHandler implements Runnable { protected final StreamSession session; protected final Socket socket; protected final int protocolVersion; private final AtomicReference<SettableFuture<?>> closeFuture = new AtomicReference<>(); protected MessageHandler(StreamSession session, Socket socket, int protocolVersion) { this.session = session; this.socket = socket; this.protocolVersion = protocolVersion; } protected abstract String name(); protected WritableByteChannel getWriteChannel() throws IOException { WritableByteChannel out = socket.getChannel(); // socket channel is null when encrypted(SSL) return out == null ? Channels.newChannel(socket.getOutputStream()) : out; } protected ReadableByteChannel getReadChannel() throws IOException { ReadableByteChannel in = socket.getChannel(); // socket channel is null when encrypted(SSL) return in == null ? Channels.newChannel(socket.getInputStream()) : in; } public void sendInitMessage(boolean isForOutgoing) throws IOException { StreamInitMessage message = new StreamInitMessage(FBUtilities.getBroadcastAddress(), session.planId(), session.description(), isForOutgoing); getWriteChannel().write(message.createMessage(false, protocolVersion)); } public void start() { new Thread(this, name() + "-" + session.peer).start(); } public ListenableFuture<?> close() { // Assume it wasn't closed. Not a huge deal if we create a future on a race SettableFuture<?> future = SettableFuture.create(); return closeFuture.compareAndSet(null, future) ? future : closeFuture.get(); } public boolean isClosed() { return closeFuture.get() != null; } protected void signalCloseDone() { closeFuture.get().set(null); // We can now close the socket try { socket.close(); } catch (IOException ignore) {} } } /** * Incoming streaming message handler */ static class IncomingMessageHandler extends MessageHandler { private final ReadableByteChannel in; IncomingMessageHandler(StreamSession session, Socket socket, int protocolVersion) throws IOException { super(session, socket, protocolVersion); this.in = getReadChannel(); } protected String name() { return "STREAM-IN"; } public void run() { while (!isClosed()) { try { // receive message StreamMessage message = StreamMessage.deserialize(in, protocolVersion, session); // Might be null if there is an error during streaming (see FileMessage.deserialize). It's ok // to ignore here since we'll have asked for a retry. if (message != null) { logger.debug("[Stream #{}] Received {}", session.planId(), message); session.messageReceived(message); } } catch (SocketException e) { // socket is closed close(); } catch (Throwable e) { session.onError(e); } } signalCloseDone(); } } /** * Outgoing file transfer thread */ static class OutgoingMessageHandler extends MessageHandler { /* * All out going messages are queued up into messageQueue. * The size will grow when received streaming request. * * Queue is also PriorityQueue so that prior messages can go out fast. */ private final PriorityBlockingQueue<StreamMessage> messageQueue = new PriorityBlockingQueue<>(64, new Comparator<StreamMessage>() { public int compare(StreamMessage o1, StreamMessage o2) { return o2.getPriority() - o1.getPriority(); } }); private final WritableByteChannel out; OutgoingMessageHandler(StreamSession session, Socket socket, int protocolVersion) throws IOException { super(session, socket, protocolVersion); this.out = getWriteChannel(); } protected String name() { return "STREAM-OUT"; } public void enqueue(StreamMessage message) { messageQueue.put(message); } public void run() { StreamMessage next; while (!isClosed()) { try { if ((next = messageQueue.poll(1, TimeUnit.SECONDS)) != null) { logger.debug("[Stream #{}] Sending {}", session.planId(), next); sendMessage(next); if (next.type == StreamMessage.Type.SESSION_FAILED) close(); } } catch (InterruptedException e) { throw new AssertionError(e); } } try { // Sends the last messages on the queue while ((next = messageQueue.poll()) != null) sendMessage(next); } finally { signalCloseDone(); } } private void sendMessage(StreamMessage message) { try { StreamMessage.serialize(message, out, protocolVersion, session); } catch (SocketException e) { session.onError(e); close(); } catch (IOException e) { session.onError(e); } } } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.containerservice; import com.fasterxml.jackson.annotation.JsonProperty; /** * Used for establishing the purchase context of any 3rd Party artifact through * MarketPlace. */ public class PurchasePlan { /** * The plan ID. */ @JsonProperty(value = "name") private String name; /** * Specifies the product of the image from the marketplace. This is the * same value as Offer under the imageReference element. */ @JsonProperty(value = "product") private String product; /** * The promotion code. */ @JsonProperty(value = "promotionCode") private String promotionCode; /** * The plan ID. */ @JsonProperty(value = "publisher") private String publisher; /** * Get the plan ID. * * @return the name value */ public String name() { return this.name; } /** * Set the plan ID. * * @param name the name value to set * @return the PurchasePlan object itself. */ public PurchasePlan withName(String name) { this.name = name; return this; } /** * Get specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element. * * @return the product value */ public String product() { return this.product; } /** * Set specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element. * * @param product the product value to set * @return the PurchasePlan object itself. */ public PurchasePlan withProduct(String product) { this.product = product; return this; } /** * Get the promotion code. * * @return the promotionCode value */ public String promotionCode() { return this.promotionCode; } /** * Set the promotion code. * * @param promotionCode the promotionCode value to set * @return the PurchasePlan object itself. */ public PurchasePlan withPromotionCode(String promotionCode) { this.promotionCode = promotionCode; return this; } /** * Get the plan ID. * * @return the publisher value */ public String publisher() { return this.publisher; } /** * Set the plan ID. * * @param publisher the publisher value to set * @return the PurchasePlan object itself. */ public PurchasePlan withPublisher(String publisher) { this.publisher = publisher; return this; } }
package io.adaptivecards.renderer.input; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.v4.app.FragmentManager; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.util.TypedValue; import android.view.ContextThemeWrapper; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import io.adaptivecards.R; import io.adaptivecards.objectmodel.ActionMode; import io.adaptivecards.objectmodel.ActionType; import io.adaptivecards.objectmodel.BaseActionElement; import io.adaptivecards.objectmodel.BaseInputElement; import io.adaptivecards.objectmodel.ContainerStyle; import io.adaptivecards.objectmodel.HeightType; import io.adaptivecards.renderer.AdaptiveWarning; import io.adaptivecards.renderer.InnerImageLoaderAsync; import io.adaptivecards.renderer.RenderedAdaptiveCard; import io.adaptivecards.renderer.action.ActionElementRenderer; import io.adaptivecards.renderer.actionhandler.ICardActionHandler; import io.adaptivecards.renderer.inputhandler.TextInputHandler; import io.adaptivecards.objectmodel.BaseCardElement; import io.adaptivecards.objectmodel.TextInput; import io.adaptivecards.objectmodel.HostConfig; import io.adaptivecards.objectmodel.TextInputStyle; import io.adaptivecards.renderer.BaseCardElementRenderer; import io.adaptivecards.renderer.registration.CardRendererRegistration; public class TextInputRenderer extends BaseCardElementRenderer { protected TextInputRenderer() { } public static TextInputRenderer getInstance() { if (s_instance == null) { s_instance = new TextInputRenderer(); } return s_instance; } protected void setTextInputStyle(EditText editText, TextInputStyle textInputStyle) { if (textInputStyle == TextInputStyle.Text) { // do nothing } else if (textInputStyle == TextInputStyle.Tel) { editText.setInputType(InputType.TYPE_CLASS_PHONE); } else if (textInputStyle == TextInputStyle.Url) { editText.setInputType(InputType.TYPE_TEXT_VARIATION_URI); } else if (textInputStyle == TextInputStyle.Email) { editText.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); } else { throw new IllegalArgumentException("Unknown TextInputStyle: " + textInputStyle.toString()); } } private class EditTextTouchListener implements View.OnTouchListener { EditTextTouchListener(Object tag) { m_tag = tag; } @Override public boolean onTouch(View v, MotionEvent event) { // Solution taken from here: https://stackoverflow.com/questions/6123973/android-edittext-vertical-scrolling-problem if (v.getTag() == m_tag) { v.getParent().requestDisallowInterceptTouchEvent(true); switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_UP: v.getParent().requestDisallowInterceptTouchEvent(false); break; } } return false; } private Object m_tag = null; } private class EditTextKeyListener implements View.OnKeyListener { EditTextKeyListener(Object tag, ICardActionHandler actionHandler, RenderedAdaptiveCard renderedCard, BaseActionElement action) { m_tag = tag; m_cardActionHandler = actionHandler; m_renderedAdaptiveCard = renderedCard; m_action = action; } @Override public boolean onKey(View view, int i, KeyEvent keyEvent) { if(view.getTag() == m_tag) { if(keyEvent.getAction() == KeyEvent.ACTION_DOWN && i == KeyEvent.KEYCODE_ENTER && m_action.GetElementType() == ActionType.Submit) { m_cardActionHandler.onAction(m_action, m_renderedAdaptiveCard); return true; } } return false; } private Object m_tag = null; private ICardActionHandler m_cardActionHandler; private RenderedAdaptiveCard m_renderedAdaptiveCard = null; private BaseActionElement m_action = null; } protected EditText renderInternal( RenderedAdaptiveCard renderedCard, Context context, ViewGroup viewGroup, BaseInputElement baseInputElement, String value, String placeHolder, final TextInputHandler textInputHandler, HostConfig hostConfig) { EditText editText = new EditText(context); textInputHandler.setView(editText); editText.setTag(textInputHandler); editText.setTextColor(Color.BLACK); renderedCard.registerInputHandler(textInputHandler); if (!TextUtils.isEmpty(value)) { editText.setText(value); } if (!TextUtils.isEmpty(placeHolder)) { editText.setHint(placeHolder); } editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { CardRendererRegistration.getInstance().notifyInputChange(textInputHandler.getId(), textInputHandler.getInput()); } }); TextInput textInput = (TextInput)baseInputElement; BaseActionElement action = textInput.GetInlineAction(); LinearLayout textInputViewGroup = null; if(action != null) { if (hostConfig.GetActions().getShowCard().getActionMode() == ActionMode.Inline && (action.GetElementType() == ActionType.ShowCard)) { renderedCard.addWarning(new AdaptiveWarning(AdaptiveWarning.INTERACTIVITY_DISALLOWED, "Inline ShowCard not supported for InlineAction")); } else { textInputViewGroup = new LinearLayout(context); textInputViewGroup.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); editText.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); textInputViewGroup.addView(editText); Resources.Theme theme = context.getTheme(); TypedValue buttonStyle = new TypedValue(); String url = action.GetIconUrl(); if(url != null && !url.isEmpty()) { ImageButton inlineButton = null; // check for style from resources if(theme.resolveAttribute(R.attr.adaptiveInlineActionImage, buttonStyle, true)) { Context themedContext = new ContextThemeWrapper(context, R.style.adaptiveInlineActionImage); inlineButton = new ImageButton(themedContext, null, 0); } else { inlineButton = new ImageButton(context); inlineButton.setBackgroundColor(Color.TRANSPARENT); inlineButton.setPadding(16, 0, 0, 8); } InlineActionIconImageLoaderAsync imageLoader = new InlineActionIconImageLoaderAsync( renderedCard, inlineButton, url, editText ); imageLoader.execute(url); textInputViewGroup.addView(inlineButton, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0)); } else { String title = action.GetTitle(); Button inlineButton = null; // check for styles from references if(theme.resolveAttribute(R.attr.adaptiveInlineAction, buttonStyle, true)) { Context themedContext = new ContextThemeWrapper(context, R.style.adaptiveInlineAction); inlineButton = new Button(themedContext, null, 0); } else { inlineButton = new Button(context); inlineButton.setBackgroundColor(Color.TRANSPARENT); inlineButton.setTextColor(Color.BLACK); inlineButton.setPadding(16, 0, 0, 8); } inlineButton.setText(title); textInputViewGroup.addView(inlineButton, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0)); } textInputViewGroup.setGravity(Gravity.CENTER); } } if(baseInputElement.GetHeight() == HeightType.Stretch) { LinearLayout containerLayout = new LinearLayout(context); containerLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1)); if(textInputViewGroup != null) { containerLayout.addView(textInputViewGroup); } else { containerLayout.addView(editText); } viewGroup.addView(containerLayout); } else { if(textInputViewGroup != null) { viewGroup.addView(textInputViewGroup); } else { viewGroup.addView(editText); } } return editText; } @Override public View render( RenderedAdaptiveCard renderedCard, Context context, FragmentManager fragmentManager, ViewGroup viewGroup, BaseCardElement baseCardElement, ICardActionHandler cardActionHandler, HostConfig hostConfig, ContainerStyle containerStyle) { if (!hostConfig.GetSupportsInteractivity()) { renderedCard.addWarning(new AdaptiveWarning(AdaptiveWarning.INTERACTIVITY_DISALLOWED, "Input.Text is not allowed")); return null; } TextInput textInput = null; if (baseCardElement instanceof TextInput) { textInput = (TextInput) baseCardElement; } else if ((textInput = TextInput.dynamic_cast(baseCardElement)) == null) { throw new InternalError("Unable to convert BaseCardElement to TextInput object model."); } TextInputHandler textInputHandler = new TextInputHandler(textInput); setSpacingAndSeparator(context, viewGroup, textInput.GetSpacing(), textInput.GetSeparator(), hostConfig, true /* horizontal line */); final EditText editText = renderInternal( renderedCard, context, viewGroup, textInput, textInput.GetValue(), textInput.GetPlaceholder(), textInputHandler, hostConfig); editText.setSingleLine(!textInput.GetIsMultiline()); editText.setTag(textInput); BaseActionElement action = textInput.GetInlineAction(); if (textInput.GetIsMultiline()) { editText.setLines(3); // Solution taken from here: https://stackoverflow.com/questions/6123973/android-edittext-vertical-scrolling-problem editText.setOnTouchListener(new EditTextTouchListener(textInput)); } else if (action != null) { // Add KeyListener if it's single line and action is submit, so when user touches enter key, // submit action will get triggered. editText.setOnKeyListener(new EditTextKeyListener(textInput, cardActionHandler, renderedCard, action)); } setTextInputStyle(editText, textInput.GetTextInputStyle()); int maxLength = (int) Math.min(textInput.GetMaxLength(), Integer.MAX_VALUE); if (maxLength > 0) { editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)}); } if(action != null) { // adds click listeners to buttons; it iterates through subviews, and grabs the button // this way is cleaner than modifying interface to accept a cardActionHandler // the subViewGroup has two child views View subView = viewGroup.getChildAt(viewGroup.getChildCount() - 1 ); if(subView instanceof ViewGroup) { ViewGroup subViewGroup = (ViewGroup) subView; for (int index = 0; index < subViewGroup.getChildCount(); ++index) { View view = subViewGroup.getChildAt(index); if (view instanceof Button || view instanceof ImageButton) { view.setOnClickListener(new ActionElementRenderer.ButtonOnClickListener(renderedCard, action, cardActionHandler)); } } } } return editText; } private class InlineActionIconImageLoaderAsync extends InnerImageLoaderAsync { private EditText m_editText; protected InlineActionIconImageLoaderAsync(RenderedAdaptiveCard renderedCard, View containerView, String url, EditText editText) { super(renderedCard, containerView, url); m_editText = editText; } @Override protected void renderBitmap(Bitmap bitmap) { ImageButton button = (ImageButton) super.m_view; Drawable drawableIcon = new BitmapDrawable(null, bitmap); double editTextHeight = (m_editText.getLineHeight() + (int) m_editText.getLineSpacingExtra()) * 2.5; double intrinsicWidth = drawableIcon.getIntrinsicHeight(); double scaleRatio = (editTextHeight )/ drawableIcon.getIntrinsicHeight(); double imageWidth = scaleRatio * drawableIcon.getIntrinsicWidth(); button.setImageDrawable(new BitmapDrawable(null, Bitmap.createScaledBitmap(bitmap, (int)imageWidth, (int)editTextHeight, false))); } } private static TextInputRenderer s_instance = null; }
/*- * ============LICENSE_START======================================================= * SDC * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. 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. * ============LICENSE_END========================================================= */ package org.openecomp.sdc.be.model.cache.jobs; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.cache.DaoInfo; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fj.data.Either; public abstract class Job<E> { private static Logger log = LoggerFactory.getLogger(Job.class.getName()); protected DaoInfo daoInfo; protected String componentId; protected long timestamp; protected NodeTypeEnum nodeTypeEnum; protected Job(DaoInfo daoInfo, String componentId, NodeTypeEnum nodeTypeEnum, long timestamp) { this.daoInfo = daoInfo; this.componentId = componentId; this.timestamp = timestamp; this.nodeTypeEnum = nodeTypeEnum; } protected Job(DaoInfo daoInfo, Component component, NodeTypeEnum nodeTypeEnum) { this.daoInfo = daoInfo; this.componentId = component.getUniqueId(); this.timestamp = component.getLastUpdateDate(); this.nodeTypeEnum = nodeTypeEnum; } public abstract E doWork(); protected Either<ComponentMetadataData, StorageOperationStatus> getComponentMetaData(String componentId, NodeTypeEnum nodeTypeEnum) { Either<ComponentMetadataData, StorageOperationStatus> metaDataRes = daoInfo.getToscaOperationFacade().getComponentMetadata(componentId); if (metaDataRes.isRight()) { // in case we cant find the component on graph exit if (StorageOperationStatus.NOT_FOUND.equals(metaDataRes.right().value())) { log.debug("failed to locate component:{} on graph status:{}", componentId, metaDataRes.right().value()); } else { log.debug("failed to get component:{} from graph status:{}", componentId, metaDataRes.right().value()); } } return metaDataRes; } protected NodeTypeEnum getNodeTypeFromComponentType(ComponentTypeEnum type) { NodeTypeEnum result = null; switch (type) { case PRODUCT: result = NodeTypeEnum.Product; break; case RESOURCE: result = NodeTypeEnum.Resource; break; case SERVICE: result = NodeTypeEnum.Service; break; default: } return result; } }
package com.baeldung.newline; public class AddingNewLineToString { public static void main(String[] args) { String line1 = "Humpty Dumpty sat on a wall."; String line2 = "Humpty Dumpty had a great fall."; String rhyme = ""; System.out.println("***New Line in a String in Java***"); //1. Using "\n" System.out.println("1. Using \\n"); rhyme = line1 + "\n" + line2; System.out.println(rhyme); //2. Using "\r\n" System.out.println("2. Using \\r\\n"); rhyme = line1 + "\r\n" + line2; System.out.println(rhyme); //3. Using "\r" System.out.println("3. Using \\r"); rhyme = line1 + "\r" + line2; System.out.println(rhyme); //4. Using "\n\r" Note that this is not same as "\r\n" // Using "\n\r" is equivalent to adding two lines System.out.println("4. Using \\n\\r"); rhyme = line1 + "\n\r" + line2; System.out.println(rhyme); //5. Using System.lineSeparator() System.out.println("5. Using System.lineSeparator()"); rhyme = line1 + System.lineSeparator() + line2; System.out.println(rhyme); //6. Using System.getProperty("line.separator") System.out.println("6. Using System.getProperty(\"line.separator\")"); rhyme = line1 + System.getProperty("line.separator") + line2; System.out.println(rhyme); System.out.println("***HTML to rendered in a browser***"); //1. Line break for HTML using <br> System.out.println("1. Line break for HTML using <br>"); rhyme = line1 + "<br>" + line2; System.out.println(rhyme); //2. Line break for HTML using “&#10;” System.out.println("2. Line break for HTML using &#10;"); rhyme = line1 + "&#10;" + line2; System.out.println(rhyme); //3. Line break for HTML using “&#13;” System.out.println("3. Line break for HTML using &#13;"); rhyme = line1 + "&#13;" + line2; System.out.println(rhyme); //4. Line break for HTML using “&#10&#13;;” System.out.println("4. Line break for HTML using &#10;&#13;"); rhyme = line1 + "&#10;&#13;" + line2; System.out.println(rhyme); //5. Line break for HTML using \n” System.out.println("5. Line break for HTML using \\n"); rhyme = line1 + "\n" + line2; System.out.println(rhyme); } }
/** * 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.curator.x.async.modeled.details; import org.apache.curator.framework.api.transaction.CuratorOp; import org.apache.curator.framework.api.transaction.CuratorTransactionResult; import org.apache.curator.framework.listen.Listenable; import org.apache.curator.x.async.AsyncCuratorFramework; import org.apache.curator.x.async.AsyncStage; import org.apache.curator.x.async.modeled.ModelSpec; import org.apache.curator.x.async.modeled.ModeledFramework; import org.apache.curator.x.async.modeled.ZNode; import org.apache.curator.x.async.modeled.ZPath; import org.apache.curator.x.async.modeled.cached.CachedModeledFramework; import org.apache.curator.x.async.modeled.cached.ModeledCache; import org.apache.curator.x.async.modeled.cached.ModeledCacheListener; import org.apache.curator.x.async.modeled.versioned.VersionedModeledFramework; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.data.Stat; import org.apache.zookeeper.server.DataTree; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; class CachedModeledFrameworkImpl<T> implements CachedModeledFramework<T> { private final ModeledFramework<T> client; private final ModeledCacheImpl<T> cache; private final Executor executor; CachedModeledFrameworkImpl(ModeledFramework<T> client, ExecutorService executor) { this(client, new ModeledCacheImpl<>(client.unwrap().unwrap(), client.modelSpec(), executor), executor); } private CachedModeledFrameworkImpl(ModeledFramework<T> client, ModeledCacheImpl<T> cache, Executor executor) { this.client = client; this.cache = cache; this.executor = executor; } @Override public ModeledCache<T> cache() { return cache; } @Override public void start() { cache.start(); } @Override public void close() { cache.close(); } @Override public Listenable<ModeledCacheListener<T>> listenable() { return cache.listenable(); } @Override public CachedModeledFramework<T> cached() { throw new UnsupportedOperationException("Already a cached instance"); } @Override public CachedModeledFramework<T> cached(ExecutorService executor) { throw new UnsupportedOperationException("Already a cached instance"); } @Override public VersionedModeledFramework<T> versioned() { return new VersionedModeledFrameworkImpl<>(this); } @Override public AsyncCuratorFramework unwrap() { return client.unwrap(); } @Override public ModelSpec<T> modelSpec() { return client.modelSpec(); } @Override public CachedModeledFramework<T> child(Object child) { return new CachedModeledFrameworkImpl<>(client.child(child), cache, executor); } @Override public ModeledFramework<T> parent() { throw new UnsupportedOperationException("Not supported for CachedModeledFramework. Instead, call parent() on the ModeledFramework before calling cached()"); } @Override public CachedModeledFramework<T> withPath(ZPath path) { return new CachedModeledFrameworkImpl<>(client.withPath(path), cache, executor); } @Override public AsyncStage<String> set(T model) { return client.set(model); } @Override public AsyncStage<String> set(T model, Stat storingStatIn) { return client.set(model, storingStatIn); } @Override public AsyncStage<String> set(T model, Stat storingStatIn, int version) { return client.set(model, storingStatIn, version); } @Override public AsyncStage<String> set(T model, int version) { return client.set(model, version); } @Override public AsyncStage<T> read() { return internalRead(ZNode::model, this::exceptionally); } @Override public AsyncStage<T> read(Stat storingStatIn) { return internalRead(n -> { if ( storingStatIn != null ) { DataTree.copyStat(n.stat(), storingStatIn); } return n.model(); }, this::exceptionally); } @Override public AsyncStage<ZNode<T>> readAsZNode() { return internalRead(Function.identity(), this::exceptionally); } @Override public AsyncStage<T> readThrough() { return internalRead(ZNode::model, client::read); } @Override public AsyncStage<T> readThrough(Stat storingStatIn) { return internalRead(ZNode::model, () -> client.read(storingStatIn)); } @Override public AsyncStage<ZNode<T>> readThroughAsZNode() { return internalRead(Function.identity(), client::readAsZNode); } @Override public AsyncStage<List<T>> list() { List<T> children = cache.currentChildren() .values() .stream() .map(ZNode::model) .collect(Collectors.toList()); return ModelStage.completed(children); } @Override public AsyncStage<Stat> update(T model) { return client.update(model); } @Override public AsyncStage<Stat> update(T model, int version) { return client.update(model, version); } @Override public AsyncStage<Void> delete() { return client.delete(); } @Override public AsyncStage<Void> delete(int version) { return client.delete(version); } @Override public AsyncStage<Stat> checkExists() { ZPath path = client.modelSpec().path(); Optional<ZNode<T>> data = cache.currentData(path); return data.map(node -> completed(node.stat())).orElseGet(() -> completed(null)); } @Override public AsyncStage<List<ZPath>> children() { List<ZPath> paths = cache.currentChildren(client.modelSpec().path()) .keySet() .stream() .filter(path -> path.equals(cache.basePath())) .collect(Collectors.toList()); return completed(paths); } @Override public AsyncStage<List<ZNode<T>>> childrenAsZNodes() { List<ZNode<T>> nodes = cache.currentChildren(client.modelSpec().path()) .entrySet() .stream() .filter(e -> e.getKey().equals(cache.basePath())) .map(Map.Entry::getValue) .collect(Collectors.toList()); return completed(nodes); } @Override public CuratorOp createOp(T model) { return client.createOp(model); } @Override public CuratorOp updateOp(T model) { return client.updateOp(model); } @Override public CuratorOp updateOp(T model, int version) { return client.updateOp(model, version); } @Override public CuratorOp deleteOp() { return client.deleteOp(); } @Override public CuratorOp deleteOp(int version) { return client.deleteOp(version); } @Override public CuratorOp checkExistsOp() { return client.checkExistsOp(); } @Override public CuratorOp checkExistsOp(int version) { return client.checkExistsOp(version); } @Override public AsyncStage<List<CuratorTransactionResult>> inTransaction(List<CuratorOp> operations) { return client.inTransaction(operations); } private <U> AsyncStage<U> completed(U value) { return ModelStage.completed(value); } private <U> AsyncStage<U> exceptionally() { KeeperException.NoNodeException exception = new KeeperException.NoNodeException(client.modelSpec().path().fullPath()); return ModelStage.exceptionally(exception); } private <U> AsyncStage<U> internalRead(Function<ZNode<T>, U> resolver, Supplier<AsyncStage<U>> elseProc) { ZPath path = client.modelSpec().path(); Optional<ZNode<T>> data = cache.currentData(path); return data.map(node -> completed(resolver.apply(node))) .orElseGet(elseProc); } }
/* * Copyright (C) 2016 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.example.android.sunshine.sync; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.support.annotation.NonNull; import com.example.android.sunshine.data.WeatherContract; import com.firebase.jobdispatcher.Constraint; import com.firebase.jobdispatcher.Driver; import com.firebase.jobdispatcher.FirebaseJobDispatcher; import com.firebase.jobdispatcher.GooglePlayDriver; import com.firebase.jobdispatcher.Job; import com.firebase.jobdispatcher.Lifetime; import com.firebase.jobdispatcher.Trigger; import java.util.concurrent.TimeUnit; public class SunshineSyncUtils { // TODO (10) Add constant values to sync Sunshine every 3 - 4 hours private static final int SYNC_INTERVAL_HOURS = 3; private static final int SYNC_INTERVAL_SECONDS = (int) TimeUnit.HOURS.toSeconds(SYNC_INTERVAL_HOURS); private static final int SYNC_FLEXTIME_SECONDS = SYNC_INTERVAL_SECONDS / 3; private static boolean sInitialized; // TODO (11) Add a sync tag to identify our sync job private static final String SUNSHINE_SYNC_TAG = "sunshine-sync"; // TODO (12) Create a method to schedule our periodic weather sync static void scheduleFirebaseJobDispatcherSync(@NonNull final Context context) { Driver driver = new GooglePlayDriver(context); FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver); /* Create the Job to periodically sync Sunshine */ Job syncSunshineJob = dispatcher.newJobBuilder() /* The Service that will be used to sync Sunshine's data */ .setService(SunshineFirebaseJobService.class) /* Set the UNIQUE tag used to identify this Job */ .setTag(SUNSHINE_SYNC_TAG) /* * Network constraints on which this Job should run. We choose to run on any * network, but you can also choose to run only on un-metered networks or when the * device is charging. It might be a good idea to include a preference for this, * as some users may not want to download any data on their mobile plan. ($$$) */ .setConstraints(Constraint.ON_ANY_NETWORK) /* * setLifetime sets how long this job should persist. The options are to keep the * Job "forever" or to have it die the next time the device boots up. */ .setLifetime(Lifetime.FOREVER) /* * We want Sunshine's weather data to stay up to date, so we tell this Job to recur. */ .setRecurring(true) /* * We want the weather data to be synced every 3 to 4 hours. The first argument for * Trigger's static executionWindow method is the start of the time frame when the * sync should be performed. The second argument is the latest point in time at * which the data should be synced. Please note that this end time is not * guaranteed, but is more of a guideline for FirebaseJobDispatcher to go off of. */ .setTrigger(Trigger.executionWindow( SYNC_INTERVAL_SECONDS, SYNC_INTERVAL_SECONDS + SYNC_FLEXTIME_SECONDS)) /* * If a Job with the tag with provided already exists, this new job will replace * the old one. */ .setReplaceCurrent(true) /* Once the Job is ready, call the builder's build method to return the Job */ .build(); /* Schedule the Job with the dispatcher */ dispatcher.schedule(syncSunshineJob); } /** * Creates periodic sync tasks and checks to see if an immediate sync is required. If an * immediate sync is required, this method will take care of making sure that sync occurs. * * @param context Context that will be passed to other methods and used to access the * ContentResolver */ synchronized public static void initialize(@NonNull final Context context) { /* * Only perform initialization once per app lifetime. If initialization has already been * performed, we have nothing to do in this method. */ if (sInitialized) return; sInitialized = true; // TODO (13) Call the method you created to schedule a periodic weather sync scheduleFirebaseJobDispatcherSync(context); /* * We need to check to see if our ContentProvider has data to display in our forecast * list. However, performing a query on the main thread is a bad idea as this may * cause our UI to lag. Therefore, we create a thread in which we will run the query * to check the contents of our ContentProvider. */ Thread checkForEmpty = new Thread(new Runnable() { @Override public void run() { /* URI for every row of weather data in our weather table*/ Uri forecastQueryUri = WeatherContract.WeatherEntry.CONTENT_URI; /* * Since this query is going to be used only as a check to see if we have any * data (rather than to display data), we just need to PROJECT the ID of each * row. In our queries where we display data, we need to PROJECT more columns * to determine what weather details need to be displayed. */ String[] projectionColumns = {WeatherContract.WeatherEntry._ID}; String selectionStatement = WeatherContract.WeatherEntry .getSqlSelectForTodayOnwards(); /* Here, we perform the query to check to see if we have any weather data */ Cursor cursor = context.getContentResolver().query( forecastQueryUri, projectionColumns, selectionStatement, null, null); /* * A Cursor object can be null for various different reasons. A few are * listed below. * * 1) Invalid URI * 2) A certain ContentProvider's query method returns null * 3) A RemoteException was thrown. * * Bottom line, it is generally a good idea to check if a Cursor returned * from a ContentResolver is null. * * If the Cursor was null OR if it was empty, we need to sync immediately to * be able to display data to the user. */ if (null == cursor || cursor.getCount() == 0) { startImmediateSync(context); } /* Make sure to close the Cursor to avoid memory leaks! */ cursor.close(); } }); /* Finally, once the thread is prepared, fire it off to perform our checks. */ checkForEmpty.start(); } /** * Helper method to perform a sync immediately using an IntentService for asynchronous * execution. * * @param context The Context used to start the IntentService for the sync. */ public static void startImmediateSync(@NonNull final Context context) { Intent intentToSyncImmediately = new Intent(context, SunshineSyncIntentService.class); context.startService(intentToSyncImmediately); } }
/* * Copyright 2018 JDCLOUD.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. * * Redis Instance API * 缓存Redis实例的创建、删除、修改基本信息、设置密码、变配、实例列表、备份、配置参数等接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ package com.jdcloud.sdk.service.redis.model; import com.jdcloud.sdk.annotation.Required; import com.jdcloud.sdk.service.JdcloudRequest; /** * 查询缓存分析任务详情,最多查询到30天前的数据 */ public class DescribeCacheAnalysisResultRequest extends JdcloudRequest implements java.io.Serializable { private static final long serialVersionUID = 1L; /** * 缓存Redis实例所在区域的Region ID。目前有华北-北京、华南-广州、华东-上海三个区域,Region ID分别为cn-north-1、cn-south-1、cn-east-2 * Required:true */ @Required private String regionId; /** * 缓存Redis实例ID,是访问实例的唯一标识 * Required:true */ @Required private String cacheInstanceId; /** * 查询缓存分析任务详情的任务ID * Required:true */ @Required private String taskId; /** * get 缓存Redis实例所在区域的Region ID。目前有华北-北京、华南-广州、华东-上海三个区域,Region ID分别为cn-north-1、cn-south-1、cn-east-2 * * @return */ public String getRegionId() { return regionId; } /** * set 缓存Redis实例所在区域的Region ID。目前有华北-北京、华南-广州、华东-上海三个区域,Region ID分别为cn-north-1、cn-south-1、cn-east-2 * * @param regionId */ public void setRegionId(String regionId) { this.regionId = regionId; } /** * get 缓存Redis实例ID,是访问实例的唯一标识 * * @return */ public String getCacheInstanceId() { return cacheInstanceId; } /** * set 缓存Redis实例ID,是访问实例的唯一标识 * * @param cacheInstanceId */ public void setCacheInstanceId(String cacheInstanceId) { this.cacheInstanceId = cacheInstanceId; } /** * get 查询缓存分析任务详情的任务ID * * @return */ public String getTaskId() { return taskId; } /** * set 查询缓存分析任务详情的任务ID * * @param taskId */ public void setTaskId(String taskId) { this.taskId = taskId; } /** * set 缓存Redis实例所在区域的Region ID。目前有华北-北京、华南-广州、华东-上海三个区域,Region ID分别为cn-north-1、cn-south-1、cn-east-2 * * @param regionId */ public DescribeCacheAnalysisResultRequest regionId(String regionId) { this.regionId = regionId; return this; } /** * set 缓存Redis实例ID,是访问实例的唯一标识 * * @param cacheInstanceId */ public DescribeCacheAnalysisResultRequest cacheInstanceId(String cacheInstanceId) { this.cacheInstanceId = cacheInstanceId; return this; } /** * set 查询缓存分析任务详情的任务ID * * @param taskId */ public DescribeCacheAnalysisResultRequest taskId(String taskId) { this.taskId = taskId; return this; } }
package org.apache.helix; /* * 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.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.I0Itec.zkclient.IZkChildListener; import org.I0Itec.zkclient.IZkDataListener; import org.I0Itec.zkclient.IZkStateListener; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.manager.zk.ZkClient; import org.apache.helix.manager.zk.client.HelixZkClient; import org.apache.helix.manager.zk.zookeeper.ZkConnection; import org.apache.helix.model.ExternalView; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.ZooKeeper.States; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; public class ZkTestHelper { private static Logger LOG = LoggerFactory.getLogger(ZkTestHelper.class); private static ExecutorService _executor = Executors.newSingleThreadExecutor(); static { // Logger.getRootLogger().setLevel(Level.DEBUG); } /** * Simulate a zk state change by calling {@link ZkClient#process(WatchedEvent)} directly */ public static void simulateZkStateReconnected(HelixZkClient client) { ZkClient zkClient = (ZkClient) client; WatchedEvent event = new WatchedEvent(EventType.None, KeeperState.Disconnected, null); zkClient.process(event); event = new WatchedEvent(EventType.None, KeeperState.SyncConnected, null); zkClient.process(event); } /** * Get zk connection session id * @param client * @return */ public static String getSessionId(HelixZkClient client) { ZkConnection connection = (ZkConnection) ((ZkClient) client).getConnection(); ZooKeeper curZookeeper = connection.getZookeeper(); return Long.toHexString(curZookeeper.getSessionId()); } /** * Expire current zk session and wait for {@link IZkStateListener#handleNewSession()} invoked * @param client * @throws Exception */ public static void disconnectSession(HelixZkClient client) throws Exception { final ZkClient zkClient = (ZkClient) client; IZkStateListener listener = new IZkStateListener() { @Override public void handleStateChanged(KeeperState state) throws Exception { // System.err.println("disconnectSession handleStateChanged. state: " + state); } @Override public void handleNewSession() throws Exception { // make sure zkclient is connected again zkClient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.SECONDS); ZkConnection connection = ((ZkConnection) zkClient.getConnection()); ZooKeeper curZookeeper = connection.getZookeeper(); LOG.info("handleNewSession. sessionId: " + Long.toHexString(curZookeeper.getSessionId())); } @Override public void handleSessionEstablishmentError(Throwable var1) throws Exception { } }; zkClient.subscribeStateChanges(listener); ZkConnection connection = ((ZkConnection) zkClient.getConnection()); ZooKeeper curZookeeper = connection.getZookeeper(); LOG.info("Before expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId())); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { LOG.info("Process watchEvent: " + event); } }; final ZooKeeper dupZookeeper = new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher, curZookeeper.getSessionId(), curZookeeper.getSessionPasswd()); // wait until connected, then close while (dupZookeeper.getState() != States.CONNECTED) { Thread.sleep(10); } dupZookeeper.close(); connection = (ZkConnection) zkClient.getConnection(); curZookeeper = connection.getZookeeper(); zkClient.unsubscribeStateChanges(listener); // System.err.println("zk: " + oldZookeeper); LOG.info("After expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId())); } public static void expireSession(HelixZkClient client) throws Exception { final CountDownLatch waitNewSession = new CountDownLatch(1); final ZkClient zkClient = (ZkClient) client; IZkStateListener listener = new IZkStateListener() { @Override public void handleStateChanged(KeeperState state) throws Exception { LOG.info("IZkStateListener#handleStateChanged, state: " + state); } @Override public void handleNewSession() throws Exception { // make sure zkclient is connected again zkClient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.SECONDS); ZkConnection connection = ((ZkConnection) zkClient.getConnection()); ZooKeeper curZookeeper = connection.getZookeeper(); LOG.info("handleNewSession. sessionId: " + Long.toHexString(curZookeeper.getSessionId())); waitNewSession.countDown(); } @Override public void handleSessionEstablishmentError(Throwable var1) throws Exception { } }; zkClient.subscribeStateChanges(listener); ZkConnection connection = ((ZkConnection) zkClient.getConnection()); ZooKeeper curZookeeper = connection.getZookeeper(); String oldSessionId = Long.toHexString(curZookeeper.getSessionId()); LOG.info("Before session expiry. sessionId: " + oldSessionId + ", zk: " + curZookeeper); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { LOG.info("Watcher#process, event: " + event); } }; final ZooKeeper dupZookeeper = new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher, curZookeeper.getSessionId(), curZookeeper.getSessionPasswd()); // wait until connected, then close while (dupZookeeper.getState() != States.CONNECTED) { Thread.sleep(10); } Assert.assertEquals(dupZookeeper.getState(), States.CONNECTED, "Fail to connect to zk using current session info"); dupZookeeper.close(); // make sure session expiry really happens waitNewSession.await(); zkClient.unsubscribeStateChanges(listener); connection = (ZkConnection) zkClient.getConnection(); curZookeeper = connection.getZookeeper(); String newSessionId = Long.toHexString(curZookeeper.getSessionId()); LOG.info("After session expiry. sessionId: " + newSessionId + ", zk: " + curZookeeper); Assert.assertNotSame(newSessionId, oldSessionId, "Fail to expire current session, zk: " + curZookeeper); } /** * expire zk session asynchronously * @param client * @throws Exception */ public static void asyncExpireSession(HelixZkClient client) throws Exception { final ZkClient zkClient = (ZkClient) client; ZkConnection connection = ((ZkConnection) zkClient.getConnection()); ZooKeeper curZookeeper = connection.getZookeeper(); LOG.info("Before expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId())); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { LOG.info("Process watchEvent: " + event); } }; final ZooKeeper dupZookeeper = new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher, curZookeeper.getSessionId(), curZookeeper.getSessionPasswd()); // wait until connected, then close while (dupZookeeper.getState() != States.CONNECTED) { Thread.sleep(10); } dupZookeeper.close(); connection = (ZkConnection) zkClient.getConnection(); curZookeeper = connection.getZookeeper(); // System.err.println("zk: " + oldZookeeper); LOG.info("After expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId())); } /* * stateMap: partition->instance->state */ public static boolean verifyState(HelixZkClient zkclient, String clusterName, String resourceName, Map<String, Map<String, String>> expectStateMap, String op) { boolean result = true; ZkBaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<ZNRecord>(zkclient); ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor); Builder keyBuilder = accessor.keyBuilder(); ExternalView extView = accessor.getProperty(keyBuilder.externalView(resourceName)); Map<String, Map<String, String>> actualStateMap = extView.getRecord().getMapFields(); for (String partition : actualStateMap.keySet()) { for (String expectPartiton : expectStateMap.keySet()) { if (!partition.matches(expectPartiton)) { continue; } Map<String, String> actualInstanceStateMap = actualStateMap.get(partition); Map<String, String> expectInstanceStateMap = expectStateMap.get(expectPartiton); for (String instance : actualInstanceStateMap.keySet()) { for (String expectInstance : expectStateMap.get(expectPartiton).keySet()) { if (!instance.matches(expectInstance)) { continue; } String actualState = actualInstanceStateMap.get(instance); String expectState = expectInstanceStateMap.get(expectInstance); boolean equals = expectState.equals(actualState); if (op.equals("==") && !equals || op.equals("!=") && equals) { System.out.println(partition + "/" + instance + " state mismatch. actual state: " + actualState + ", but expect: " + expectState + ", op: " + op); result = false; } } } } } return result; } /** * return the number of listeners on given zk-path * @param zkAddr * @param path * @return * @throws Exception */ public static int numberOfListeners(String zkAddr, String path) throws Exception { Map<String, Set<String>> listenerMap = getListenersByZkPath(zkAddr); if (listenerMap.containsKey(path)) { return listenerMap.get(path).size(); } return 0; } /** * return a map from zk-path to a set of zk-session-id that put watches on the zk-path * @param zkAddr * @return * @throws Exception */ public static Map<String, Set<String>> getListenersByZkPath(String zkAddr) throws Exception { String splits[] = zkAddr.split(":"); Map<String, Set<String>> listenerMap = new TreeMap<String, Set<String>>(); Socket sock = null; int retry = 5; while (retry > 0) { try { sock = new Socket(splits[0], Integer.parseInt(splits[1])); PrintWriter out = new PrintWriter(sock.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream())); out.println("wchp"); listenerMap.clear(); String lastPath = null; String line = in.readLine(); while (line != null) { line = line.trim(); if (line.startsWith("/")) { lastPath = line; if (!listenerMap.containsKey(lastPath)) { listenerMap.put(lastPath, new TreeSet<String>()); } } else if (line.startsWith("0x")) { if (lastPath != null && listenerMap.containsKey(lastPath)) { listenerMap.get(lastPath).add(line); } else { LOG.error("Not path associated with listener sessionId: " + line + ", lastPath: " + lastPath); } } else { // LOG.error("unrecognized line: " + line); } line = in.readLine(); } break; } catch (Exception e) { // sometimes in test, we see connection-reset exceptions when in.readLine() // so add this retry logic retry--; } finally { if (sock != null) sock.close(); } } return listenerMap; } /** * return a map from session-id to a set of zk-path that the session has watches on * @return */ public static Map<String, Set<String>> getListenersBySession(String zkAddr) throws Exception { Map<String, Set<String>> listenerMapByInstance = getListenersByZkPath(zkAddr); // convert to index by sessionId Map<String, Set<String>> listenerMapBySession = new TreeMap<>(); for (String path : listenerMapByInstance.keySet()) { for (String sessionId : listenerMapByInstance.get(path)) { if (!listenerMapBySession.containsKey(sessionId)) { listenerMapBySession.put(sessionId, new TreeSet<String>()); } listenerMapBySession.get(sessionId).add(path); } } return listenerMapBySession; } static java.lang.reflect.Field getField(Class clazz, String fieldName) throws NoSuchFieldException { try { return clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { Class superClass = clazz.getSuperclass(); if (superClass == null) { throw e; } else { return getField(superClass, fieldName); } } } public static Map<String, List<String>> getZkWatch(HelixZkClient client) throws Exception { Map<String, List<String>> lists = new HashMap<String, List<String>>(); ZkClient zkClient = (ZkClient) client; ZkConnection connection = ((ZkConnection) zkClient.getConnection()); ZooKeeper zk = connection.getZookeeper(); java.lang.reflect.Field field = getField(zk.getClass(), "watchManager"); field.setAccessible(true); Object watchManager = field.get(zk); java.lang.reflect.Field field2 = getField(watchManager.getClass(), "dataWatches"); field2.setAccessible(true); HashMap<String, Set<Watcher>> dataWatches = (HashMap<String, Set<Watcher>>) field2.get(watchManager); field2 = getField(watchManager.getClass(), "existWatches"); field2.setAccessible(true); HashMap<String, Set<Watcher>> existWatches = (HashMap<String, Set<Watcher>>) field2.get(watchManager); field2 = getField(watchManager.getClass(), "childWatches"); field2.setAccessible(true); HashMap<String, Set<Watcher>> childWatches = (HashMap<String, Set<Watcher>>) field2.get(watchManager); lists.put("dataWatches", new ArrayList<>(dataWatches.keySet())); lists.put("existWatches", new ArrayList<>(existWatches.keySet())); lists.put("childWatches", new ArrayList<>(childWatches.keySet())); return lists; } public static Map<String, Set<IZkDataListener>> getZkDataListener(HelixZkClient client) throws Exception { java.lang.reflect.Field field = getField(client.getClass(), "_dataListener"); field.setAccessible(true); Map<String, Set<IZkDataListener>> dataListener = (Map<String, Set<IZkDataListener>>) field.get(client); return dataListener; } public static Map<String, Set<IZkChildListener>> getZkChildListener(HelixZkClient client) throws Exception { java.lang.reflect.Field field = getField(client.getClass(), "_childListener"); field.setAccessible(true); Map<String, Set<IZkChildListener>> childListener = (Map<String, Set<IZkChildListener>>) field.get(client); return childListener; } public static boolean tryWaitZkEventsCleaned(HelixZkClient zkclient) throws Exception { java.lang.reflect.Field field = getField(zkclient.getClass(), "_eventThread"); field.setAccessible(true); Object eventThread = field.get(zkclient); // System.out.println("field: " + eventThread); java.lang.reflect.Field field2 = getField(eventThread.getClass(), "_events"); field2.setAccessible(true); BlockingQueue queue = (BlockingQueue) field2.get(eventThread); // System.out.println("field2: " + queue + ", " + queue.size()); if (queue == null) { LOG.error("fail to get event-queue from zkclient. skip waiting"); return false; } for (int i = 0; i < 20; i++) { if (queue.size() == 0) { return true; } Thread.sleep(100); System.out.println("pending zk-events in queue: " + queue); } return false; } public static void injectExpire(HelixZkClient client) throws ExecutionException, InterruptedException { final ZkClient zkClient = (ZkClient) client; Future future = _executor.submit(new Runnable() { @Override public void run() { WatchedEvent event = new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Expired, null); zkClient.process(event); } }); future.get(); } }
/** * Copyright 2013 Canada Health Infoway, 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. * * Author: $LastChangedBy$ * Last modified: $LastChangedDate$ * Revision: $LastChangedRevision$ */ /* This class was auto-generated by the message builder generator tools. */ package ca.infoway.messagebuilder.model.pcs_mr2009_r02_05_00.claims.ficr_mt400003ca; import ca.infoway.messagebuilder.annotation.Hl7PartTypeMapping; import ca.infoway.messagebuilder.annotation.Hl7XmlMapping; import ca.infoway.messagebuilder.datatype.TN; import ca.infoway.messagebuilder.datatype.impl.TNImpl; import ca.infoway.messagebuilder.datatype.lang.TrivialName; import ca.infoway.messagebuilder.model.MessagePartBean; @Hl7PartTypeMapping({"FICR_MT400003CA.PolicyHolderOrganization"}) public class PolicyHolderOrganizationBean extends MessagePartBean implements ca.infoway.messagebuilder.model.pcs_mr2009_r02_05_00.claims.merged.PolicyHolderChoice { private static final long serialVersionUID = 20190731L; private TN name = new TNImpl(); /** * <p>Business Name: Policy Holder Organization Name</p> * * <p>Relationship: * FICR_MT400003CA.PolicyHolderOrganization.name</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ @Hl7XmlMapping({"name"}) public TrivialName getName() { return this.name.getValue(); } /** * <p>Business Name: Policy Holder Organization Name</p> * * <p>Relationship: * FICR_MT400003CA.PolicyHolderOrganization.name</p> * * <p>Conformance/Cardinality: MANDATORY (1)</p> */ public void setName(TrivialName name) { this.name.setValue(name); } }
/* * Copyright (c) 2015 Kloudtek Ltd */ package com.kloudtek.kryptotek.keystore; import com.kloudtek.util.BackendAccessException; /** * Created by yannick on 22/11/2014. */ public class KeyStoreAccessException extends BackendAccessException { public KeyStoreAccessException() { } public KeyStoreAccessException(String message) { super(message); } public KeyStoreAccessException(String message, Throwable cause) { super(message, cause); } public KeyStoreAccessException(Throwable cause) { super(cause); } }
package ooga.model.systems.creature; /** * @author Tinglong Zhu */ import java.util.List; import ooga.model.actions.NPCAction; import ooga.model.actions.ObjectSpawner; import ooga.model.annotations.Track; import ooga.model.components.MovementComponent; import ooga.model.components.MovementComponent.HorizontalMovementStatus; import ooga.model.components.MovementSequenceComponent; import ooga.model.components.PlayerComponent; import ooga.model.managers.ECManager; import ooga.model.systems.ComponentBasedSystem; import ooga.model.systems.ComponentMapper; /** * Logic for executing the NPC actions */ @Track({MovementSequenceComponent.class, PlayerComponent.class, MovementComponent.class}) public class NPCSystem extends ComponentBasedSystem { private ComponentMapper<MovementSequenceComponent> movementSequenceMapper; private ComponentMapper<MovementComponent> movementMapper; public NPCSystem(ECManager ecManager) { super(ecManager); movementSequenceMapper = getComponentMapper(MovementSequenceComponent.class); movementMapper= getComponentMapper(MovementComponent.class); } private List<MovementSequenceComponent> getMovementSequence() { return movementSequenceMapper.getComponents(); } @Override public void update(double deltaTime) { for (MovementSequenceComponent ms : getMovementSequence()) { unitUpdate(deltaTime,movementMapper.get(ms.getOwner().getId()),ms); } } private void execAction(NPCAction actionCode, double deltaTime, MovementComponent m, MovementSequenceComponent ms){ switch (actionCode.getAction()){ case "move_left": moveLeft(deltaTime,m); break; case "move_right": moveRight(deltaTime,m); break; case "stand_still": standStill(m); break; case "spawn_object": ObjectSpawner spawner = new ObjectSpawner(actionCode.getPayload(), getECManager()); spawner.handleSpawn(ms.getOwner().getId(), true); default: break; } } private void moveRight(double deltaTime, MovementComponent m){ m.setHorizontalStatus(HorizontalMovementStatus.RUNNING); m.setDirection(1); } private void standStill(MovementComponent m){ m.setHorizontalStatus(HorizontalMovementStatus.STILL); } private void moveLeft(double deltaTime, MovementComponent m){ m.setHorizontalStatus(HorizontalMovementStatus.RUNNING); m.setDirection(-1); } private void unitUpdate(double deltaTime,MovementComponent m, MovementSequenceComponent ms){ double cumTime= ms.getCumTime(); List<NPCAction> actionSequence=ms.getActionSequence(); List<Double> actionTime=ms.getActualActionTime(); int actionIndex = ms.getActionIndex(); if (cumTime < actionTime.get(actionIndex)) { cumTime += deltaTime; ms.setCumTime(cumTime); } else { ms.setCumTime(0); actionIndex++; actionIndex=actionIndex%actionSequence.size(); ms.setActionIndex(actionIndex); } if (actionIndex >= actionSequence.size()) { ms.setActionIndex(0); } execAction(actionSequence.get(actionIndex), deltaTime, m, ms); } }