text
stringlengths
7
1.01M
package com.yuta.foods.adapter; import java.util.List; import android.app.Activity; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.yuta.foods.R; import com.yuta.foods.db.ListViewCache; import com.yuta.foods.model.ListFood; import com.yuta.foods.server.AsyncImageLoader; import com.yuta.foods.server.AsyncImageLoader.ImageCallback; public class ListFoodAdapter extends ArrayAdapter<ListFood>{ private ListView listView; private AsyncImageLoader asyncImageLoader; private List<ListFood> listFood; public ListFoodAdapter(Activity activity, List<ListFood> imageAndTexts, ListView listView) { super(activity, 0, imageAndTexts); this.listView = listView; asyncImageLoader = new AsyncImageLoader(); } public void setData(List<ListFood> data){ listFood = data; } public View getView(int position, View convertView, ViewGroup parent) { Activity activity = (Activity) getContext(); // Inflate the views from XML View rowView = convertView; ListViewCache viewCache; if (rowView == null) { LayoutInflater inflater = activity.getLayoutInflater(); rowView = inflater.inflate(R.layout.list_listview_layout, null); viewCache = new ListViewCache(rowView); rowView.setTag(viewCache); } else { viewCache = (ListViewCache) rowView.getTag(); } ListFood imageAndText = getItem(position); // Load the image and set it on the ImageView String imageUrl = imageAndText.getImg(); ImageView imageView = viewCache.getImg(); imageView.setTag(imageUrl); Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback() { public void imageLoaded(Drawable imageDrawable, String imageUrl) { ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl); if (imageViewByTag != null) { imageViewByTag.setImageDrawable(imageDrawable); } } }); if (cachedImage == null) { imageView.setImageResource(R.drawable.refresh); }else{ imageView.setImageDrawable(cachedImage); } // Set the text on the TextView TextView name = viewCache.getName(); name.setText(imageAndText.getName()); TextView tag = viewCache.getTag(); tag.setText(imageAndText.getTag()); return rowView; } }
package com.gldb.data; import java.math.BigDecimal; import java.util.Date; /** * GLDB.Tbdeposit * 10/09/2018 18:35:31 * */ public class Tbdeposit { private Integer id; private String productCode; private String subProductCode; private String accountNo; private String accountnoata; private String accountName; private String slaidNo; private String employeeNo; private BigDecimal accountBalance; private BigDecimal floatAmount; private Integer accountStatus; private Date statusDate; private BigDecimal pledgeAmount; private String pledgeSchedule; private BigDecimal accumulatedBalance; private Integer daysElapsed; private BigDecimal averageDailyBalance; private BigDecimal mtdint; private BigDecimal btdint; private BigDecimal mtdcredits; private BigDecimal ytdcredits; private BigDecimal btdcredits; private BigDecimal mtddebits; private BigDecimal ytddebits; private BigDecimal btddebits; private Integer totalNoCredits; private Integer totalNoDebits; private Date bookDate; private BigDecimal intRate; private BigDecimal wtaxrate; private Integer term; private Date maturityDate; private String compoundingFreq; private BigDecimal maintainingBalance; private BigDecimal toEarnInterestBalance; private String posttx; private Integer oldstatus; private Date oldStatusDate; private String jointAcctType; private Integer ownershipType; private BigDecimal placementAmt; private BigDecimal lessWtaxAmt; private BigDecimal matAmt; private BigDecimal placeholdAmt; private String createdBy; private String watchlistCode; private String unit; private String instcode; private Integer alertflag; private String alertmessage; private Integer alertlevel; private String dispoflag; private String dispofreetext; private String tdcno; private Integer tdcreleaseind; private Integer jrnlno; private Integer xbelowmin; private Integer xreturnchk; private BigDecimal int4credit; private BigDecimal prevmonthadb; private BigDecimal prevmtdint; private BigDecimal prevint4credit; private String lasttxdate; private String lasttxcode; private Integer minbalctr; private Integer chk4clr; private BigDecimal adbavailbal; private BigDecimal adbbookbal; private BigDecimal eomadbavailbal; private BigDecimal eomadbbookbal; private BigDecimal eoyadbavailbal; private BigDecimal eoyadbbookbal; private BigDecimal passbookbal; private BigDecimal ytdadbavailbal; private BigDecimal ytdaddbookbal; private BigDecimal ytdaccumcredit; private BigDecimal ytdaccumdebit; private BigDecimal ytdintearned; private BigDecimal mtdintearned; private BigDecimal earmarkbal; private Integer freezeind; private Date freezeexpdt; private Integer freezeid; private String regioncode; private String areacode; private BigDecimal bpapproved; private Date bpexpirydt; private String bpstatus; private BigDecimal bpavailed; private BigDecimal garnishedbal; private BigDecimal accumbook; private BigDecimal accumavail; private String soadispo; private String solicitingofficer; private String referralofficer; private String campaign; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public String getSubProductCode() { return subProductCode; } public void setSubProductCode(String subProductCode) { this.subProductCode = subProductCode; } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public String getAccountnoata() { return accountnoata; } public void setAccountnoata(String accountnoata) { this.accountnoata = accountnoata; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public String getSlaidNo() { return slaidNo; } public void setSlaidNo(String slaidNo) { this.slaidNo = slaidNo; } public String getEmployeeNo() { return employeeNo; } public void setEmployeeNo(String employeeNo) { this.employeeNo = employeeNo; } public BigDecimal getAccountBalance() { return accountBalance; } public void setAccountBalance(BigDecimal accountBalance) { this.accountBalance = accountBalance; } public BigDecimal getFloatAmount() { return floatAmount; } public void setFloatAmount(BigDecimal floatAmount) { this.floatAmount = floatAmount; } public Integer getAccountStatus() { return accountStatus; } public void setAccountStatus(Integer accountStatus) { this.accountStatus = accountStatus; } public Date getStatusDate() { return statusDate; } public void setStatusDate(Date statusDate) { this.statusDate = statusDate; } public BigDecimal getPledgeAmount() { return pledgeAmount; } public void setPledgeAmount(BigDecimal pledgeAmount) { this.pledgeAmount = pledgeAmount; } public String getPledgeSchedule() { return pledgeSchedule; } public void setPledgeSchedule(String pledgeSchedule) { this.pledgeSchedule = pledgeSchedule; } public BigDecimal getAccumulatedBalance() { return accumulatedBalance; } public void setAccumulatedBalance(BigDecimal accumulatedBalance) { this.accumulatedBalance = accumulatedBalance; } public Integer getDaysElapsed() { return daysElapsed; } public void setDaysElapsed(Integer daysElapsed) { this.daysElapsed = daysElapsed; } public BigDecimal getAverageDailyBalance() { return averageDailyBalance; } public void setAverageDailyBalance(BigDecimal averageDailyBalance) { this.averageDailyBalance = averageDailyBalance; } public BigDecimal getMtdint() { return mtdint; } public void setMtdint(BigDecimal mtdint) { this.mtdint = mtdint; } public BigDecimal getBtdint() { return btdint; } public void setBtdint(BigDecimal btdint) { this.btdint = btdint; } public BigDecimal getMtdcredits() { return mtdcredits; } public void setMtdcredits(BigDecimal mtdcredits) { this.mtdcredits = mtdcredits; } public BigDecimal getYtdcredits() { return ytdcredits; } public void setYtdcredits(BigDecimal ytdcredits) { this.ytdcredits = ytdcredits; } public BigDecimal getBtdcredits() { return btdcredits; } public void setBtdcredits(BigDecimal btdcredits) { this.btdcredits = btdcredits; } public BigDecimal getMtddebits() { return mtddebits; } public void setMtddebits(BigDecimal mtddebits) { this.mtddebits = mtddebits; } public BigDecimal getYtddebits() { return ytddebits; } public void setYtddebits(BigDecimal ytddebits) { this.ytddebits = ytddebits; } public BigDecimal getBtddebits() { return btddebits; } public void setBtddebits(BigDecimal btddebits) { this.btddebits = btddebits; } public Integer getTotalNoCredits() { return totalNoCredits; } public void setTotalNoCredits(Integer totalNoCredits) { this.totalNoCredits = totalNoCredits; } public Integer getTotalNoDebits() { return totalNoDebits; } public void setTotalNoDebits(Integer totalNoDebits) { this.totalNoDebits = totalNoDebits; } public Date getBookDate() { return bookDate; } public void setBookDate(Date bookDate) { this.bookDate = bookDate; } public BigDecimal getIntRate() { return intRate; } public void setIntRate(BigDecimal intRate) { this.intRate = intRate; } public BigDecimal getWtaxrate() { return wtaxrate; } public void setWtaxrate(BigDecimal wtaxrate) { this.wtaxrate = wtaxrate; } public Integer getTerm() { return term; } public void setTerm(Integer term) { this.term = term; } public Date getMaturityDate() { return maturityDate; } public void setMaturityDate(Date maturityDate) { this.maturityDate = maturityDate; } public String getCompoundingFreq() { return compoundingFreq; } public void setCompoundingFreq(String compoundingFreq) { this.compoundingFreq = compoundingFreq; } public BigDecimal getMaintainingBalance() { return maintainingBalance; } public void setMaintainingBalance(BigDecimal maintainingBalance) { this.maintainingBalance = maintainingBalance; } public BigDecimal getToEarnInterestBalance() { return toEarnInterestBalance; } public void setToEarnInterestBalance(BigDecimal toEarnInterestBalance) { this.toEarnInterestBalance = toEarnInterestBalance; } public String getPosttx() { return posttx; } public void setPosttx(String posttx) { this.posttx = posttx; } public Integer getOldstatus() { return oldstatus; } public void setOldstatus(Integer oldstatus) { this.oldstatus = oldstatus; } public Date getOldStatusDate() { return oldStatusDate; } public void setOldStatusDate(Date oldStatusDate) { this.oldStatusDate = oldStatusDate; } public String getJointAcctType() { return jointAcctType; } public void setJointAcctType(String jointAcctType) { this.jointAcctType = jointAcctType; } public Integer getOwnershipType() { return ownershipType; } public void setOwnershipType(Integer ownershipType) { this.ownershipType = ownershipType; } public BigDecimal getPlacementAmt() { return placementAmt; } public void setPlacementAmt(BigDecimal placementAmt) { this.placementAmt = placementAmt; } public BigDecimal getLessWtaxAmt() { return lessWtaxAmt; } public void setLessWtaxAmt(BigDecimal lessWtaxAmt) { this.lessWtaxAmt = lessWtaxAmt; } public BigDecimal getMatAmt() { return matAmt; } public void setMatAmt(BigDecimal matAmt) { this.matAmt = matAmt; } public BigDecimal getPlaceholdAmt() { return placeholdAmt; } public void setPlaceholdAmt(BigDecimal placeholdAmt) { this.placeholdAmt = placeholdAmt; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public String getWatchlistCode() { return watchlistCode; } public void setWatchlistCode(String watchlistCode) { this.watchlistCode = watchlistCode; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getInstcode() { return instcode; } public void setInstcode(String instcode) { this.instcode = instcode; } public Integer getAlertflag() { return alertflag; } public void setAlertflag(Integer alertflag) { this.alertflag = alertflag; } public String getAlertmessage() { return alertmessage; } public void setAlertmessage(String alertmessage) { this.alertmessage = alertmessage; } public Integer getAlertlevel() { return alertlevel; } public void setAlertlevel(Integer alertlevel) { this.alertlevel = alertlevel; } public String getDispoflag() { return dispoflag; } public void setDispoflag(String dispoflag) { this.dispoflag = dispoflag; } public String getDispofreetext() { return dispofreetext; } public void setDispofreetext(String dispofreetext) { this.dispofreetext = dispofreetext; } public String getTdcno() { return tdcno; } public void setTdcno(String tdcno) { this.tdcno = tdcno; } public Integer getTdcreleaseind() { return tdcreleaseind; } public void setTdcreleaseind(Integer tdcreleaseind) { this.tdcreleaseind = tdcreleaseind; } public Integer getJrnlno() { return jrnlno; } public void setJrnlno(Integer jrnlno) { this.jrnlno = jrnlno; } public Integer getXbelowmin() { return xbelowmin; } public void setXbelowmin(Integer xbelowmin) { this.xbelowmin = xbelowmin; } public Integer getXreturnchk() { return xreturnchk; } public void setXreturnchk(Integer xreturnchk) { this.xreturnchk = xreturnchk; } public BigDecimal getInt4credit() { return int4credit; } public void setInt4credit(BigDecimal int4credit) { this.int4credit = int4credit; } public BigDecimal getPrevmonthadb() { return prevmonthadb; } public void setPrevmonthadb(BigDecimal prevmonthadb) { this.prevmonthadb = prevmonthadb; } public BigDecimal getPrevmtdint() { return prevmtdint; } public void setPrevmtdint(BigDecimal prevmtdint) { this.prevmtdint = prevmtdint; } public BigDecimal getPrevint4credit() { return prevint4credit; } public void setPrevint4credit(BigDecimal prevint4credit) { this.prevint4credit = prevint4credit; } public String getLasttxdate() { return lasttxdate; } public void setLasttxdate(String lasttxdate) { this.lasttxdate = lasttxdate; } public String getLasttxcode() { return lasttxcode; } public void setLasttxcode(String lasttxcode) { this.lasttxcode = lasttxcode; } public Integer getMinbalctr() { return minbalctr; } public void setMinbalctr(Integer minbalctr) { this.minbalctr = minbalctr; } public Integer getChk4clr() { return chk4clr; } public void setChk4clr(Integer chk4clr) { this.chk4clr = chk4clr; } public BigDecimal getAdbavailbal() { return adbavailbal; } public void setAdbavailbal(BigDecimal adbavailbal) { this.adbavailbal = adbavailbal; } public BigDecimal getAdbbookbal() { return adbbookbal; } public void setAdbbookbal(BigDecimal adbbookbal) { this.adbbookbal = adbbookbal; } public BigDecimal getEomadbavailbal() { return eomadbavailbal; } public void setEomadbavailbal(BigDecimal eomadbavailbal) { this.eomadbavailbal = eomadbavailbal; } public BigDecimal getEomadbbookbal() { return eomadbbookbal; } public void setEomadbbookbal(BigDecimal eomadbbookbal) { this.eomadbbookbal = eomadbbookbal; } public BigDecimal getEoyadbavailbal() { return eoyadbavailbal; } public void setEoyadbavailbal(BigDecimal eoyadbavailbal) { this.eoyadbavailbal = eoyadbavailbal; } public BigDecimal getEoyadbbookbal() { return eoyadbbookbal; } public void setEoyadbbookbal(BigDecimal eoyadbbookbal) { this.eoyadbbookbal = eoyadbbookbal; } public BigDecimal getPassbookbal() { return passbookbal; } public void setPassbookbal(BigDecimal passbookbal) { this.passbookbal = passbookbal; } public BigDecimal getYtdadbavailbal() { return ytdadbavailbal; } public void setYtdadbavailbal(BigDecimal ytdadbavailbal) { this.ytdadbavailbal = ytdadbavailbal; } public BigDecimal getYtdaddbookbal() { return ytdaddbookbal; } public void setYtdaddbookbal(BigDecimal ytdaddbookbal) { this.ytdaddbookbal = ytdaddbookbal; } public BigDecimal getYtdaccumcredit() { return ytdaccumcredit; } public void setYtdaccumcredit(BigDecimal ytdaccumcredit) { this.ytdaccumcredit = ytdaccumcredit; } public BigDecimal getYtdaccumdebit() { return ytdaccumdebit; } public void setYtdaccumdebit(BigDecimal ytdaccumdebit) { this.ytdaccumdebit = ytdaccumdebit; } public BigDecimal getYtdintearned() { return ytdintearned; } public void setYtdintearned(BigDecimal ytdintearned) { this.ytdintearned = ytdintearned; } public BigDecimal getMtdintearned() { return mtdintearned; } public void setMtdintearned(BigDecimal mtdintearned) { this.mtdintearned = mtdintearned; } public BigDecimal getEarmarkbal() { return earmarkbal; } public void setEarmarkbal(BigDecimal earmarkbal) { this.earmarkbal = earmarkbal; } public Integer getFreezeind() { return freezeind; } public void setFreezeind(Integer freezeind) { this.freezeind = freezeind; } public Date getFreezeexpdt() { return freezeexpdt; } public void setFreezeexpdt(Date freezeexpdt) { this.freezeexpdt = freezeexpdt; } public Integer getFreezeid() { return freezeid; } public void setFreezeid(Integer freezeid) { this.freezeid = freezeid; } public String getRegioncode() { return regioncode; } public void setRegioncode(String regioncode) { this.regioncode = regioncode; } public String getAreacode() { return areacode; } public void setAreacode(String areacode) { this.areacode = areacode; } public BigDecimal getBpapproved() { return bpapproved; } public void setBpapproved(BigDecimal bpapproved) { this.bpapproved = bpapproved; } public Date getBpexpirydt() { return bpexpirydt; } public void setBpexpirydt(Date bpexpirydt) { this.bpexpirydt = bpexpirydt; } public String getBpstatus() { return bpstatus; } public void setBpstatus(String bpstatus) { this.bpstatus = bpstatus; } public BigDecimal getBpavailed() { return bpavailed; } public void setBpavailed(BigDecimal bpavailed) { this.bpavailed = bpavailed; } public BigDecimal getGarnishedbal() { return garnishedbal; } public void setGarnishedbal(BigDecimal garnishedbal) { this.garnishedbal = garnishedbal; } public BigDecimal getAccumbook() { return accumbook; } public void setAccumbook(BigDecimal accumbook) { this.accumbook = accumbook; } public BigDecimal getAccumavail() { return accumavail; } public void setAccumavail(BigDecimal accumavail) { this.accumavail = accumavail; } public String getSoadispo() { return soadispo; } public void setSoadispo(String soadispo) { this.soadispo = soadispo; } public String getSolicitingofficer() { return solicitingofficer; } public void setSolicitingofficer(String solicitingofficer) { this.solicitingofficer = solicitingofficer; } public String getReferralofficer() { return referralofficer; } public void setReferralofficer(String referralofficer) { this.referralofficer = referralofficer; } public String getCampaign() { return campaign; } public void setCampaign(String campaign) { this.campaign = campaign; } }
/* Code adapted from Medium.com * "Creating Your First Blockchain with Java. Part 1." */ package app; import java.util.Date; public class Block { public String hash; public String previousHash; public String claimHash; public long timestamp; public Block(Claim claim, String previousHash) { this.claimHash = claim.toHash(); this.previousHash = previousHash; this.timestamp = new Date().getTime(); this.hash = hash(); } public Block(Block toCopy) { this.claimHash = toCopy.claimHash; this.previousHash = toCopy.previousHash; this.timestamp = toCopy.timestamp; this.hash = toCopy.hash; } public Block(String previousHash, String hash, String claimHash) { this.previousHash = previousHash; this.hash = hash; this.claimHash = claimHash; } public String hash() { String toReturn = StringUtil.encode(previousHash + Long.toString(timestamp) + claimHash.toString() ); return toReturn; } public String toString() { String toReturn = ""; toReturn += "Previous Hash: " + previousHash + "\n"; toReturn += "Hash: " + hash + "\n"; toReturn += "Claim Hash: " + claimHash.toString() + "\n"; return toReturn; } }
package com.smartbear.readyapi4j.support; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.smartbear.readyapi4j.client.model.TestJobReport; import com.smartbear.readyapi4j.client.model.TestSuiteResultReport; import com.smartbear.readyapi4j.execution.Execution; import com.smartbear.readyapi4j.execution.ExecutionListener; import com.smartbear.readyapi4j.result.TestStepResult; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.util.List; import java.util.Map; import static com.smartbear.readyapi4j.support.RecipeLogger.createFileName; /** * ExecutionListener that writes response HAR entries to a single log file after execution */ public class ExecutionLogger implements ExecutionListener { private final static Logger LOG = LoggerFactory.getLogger(ExecutionLogger.class); public static final String DEFAULT_EXTENSION = "har"; private final String targetFolder; private final String extension; public ExecutionLogger(String targetFolder, String extension) { this.targetFolder = targetFolder; this.extension = extension; } public ExecutionLogger(String targetFolder) { this(targetFolder, DEFAULT_EXTENSION); } @Override public void executionFinished(Execution execution) { try { File directory = new File(targetFolder); if (!directory.exists()) { directory.mkdirs(); } List<Map<Object, Object>> entries = Lists.newArrayList(); for (TestStepResult result : execution.getExecutionResult().getTestStepResults()) { entries.add(getLogDataForResult(result)); } File file; String name = createExecutionName(execution); if (StringUtils.isNotBlank(name)) { file = new File(directory, createFileName(name, '_') + "." + extension); } else { file = File.createTempFile("execution-" + execution.getId(), "." + extension, directory); } try (FileOutputStream fileOutputStream = new FileOutputStream(file)) { fileOutputStream.write(JsonUtils.pretty(entries).getBytes()); } } catch (Exception e) { LOG.error("Failed to write response logs to file", e); } } private String createExecutionName(Execution execution) { TestJobReport currentReport = execution.getCurrentReport(); String name = currentReport.getProjectName(); List<TestSuiteResultReport> testSuiteResultReports = currentReport.getTestSuiteResultReports(); if (testSuiteResultReports.size() == 1) { if (testSuiteResultReports.get(0).getTestCaseResultReports().size() == 1) { name = "TestCase " + testSuiteResultReports.get(0).getTestCaseResultReports().get(0).getTestCaseName(); } else { name = "TestSuite " + testSuiteResultReports.get(0).getTestSuiteName(); } } if (execution.getCurrentStatus() == TestJobReport.StatusEnum.FAILED) { name += "-" + execution.getCurrentStatus().name(); } return name; } private Map<Object, Object> getLogDataForResult(TestStepResult testStepResult) { Map<Object, Object> result = Maps.newConcurrentMap(); result.put("testStep", testStepResult.getTestStepName()); result.put("timeTaken", testStepResult.getTimeTaken()); result.put("status", testStepResult.getAssertionStatus()); if (testStepResult.getMessages() != null && !testStepResult.getMessages().isEmpty()) { result.put("messsages", testStepResult.getMessages()); } if (testStepResult.getHarEntry() != null) { result.put("harEntry", testStepResult.getHarEntry()); } return result; } }
package top.naccl.exception; /** * @Description: 非法请求异常 * @Author: Naccl * @Date: 2020-10-16 */ public class BadRequestException extends RuntimeException { public BadRequestException() { } public BadRequestException(String message) { super(message); } public BadRequestException(String message, Throwable cause) { super(message, cause); } }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.cwp.v20180228.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DescribeGeneralStatResponse extends AbstractModel{ /** * 云主机总数 */ @SerializedName("MachinesAll") @Expose private Long MachinesAll; /** * 云主机没有安装主机安全客户端的总数 */ @SerializedName("MachinesUninstalled") @Expose private Long MachinesUninstalled; /** * 主机安全客户端总数的总数 */ @SerializedName("AgentsAll") @Expose private Long AgentsAll; /** * 主机安全客户端在线的总数 */ @SerializedName("AgentsOnline") @Expose private Long AgentsOnline; /** * 主机安全客户端 离线+关机 的总数 */ @SerializedName("AgentsOffline") @Expose private Long AgentsOffline; /** * 主机安全客户端专业版的总数 */ @SerializedName("AgentsPro") @Expose private Long AgentsPro; /** * 主机安全客户端基础版的总数 */ @SerializedName("AgentsBasic") @Expose private Long AgentsBasic; /** * 7天内到期的预付费专业版总数 */ @SerializedName("AgentsProExpireWithInSevenDays") @Expose private Long AgentsProExpireWithInSevenDays; /** * 风险主机总数 */ @SerializedName("RiskMachine") @Expose private Long RiskMachine; /** * 已关机总数 */ @SerializedName("Shutdown") @Expose private Long Shutdown; /** * 已离线总数 */ @SerializedName("Offline") @Expose private Long Offline; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ @SerializedName("RequestId") @Expose private String RequestId; /** * Get 云主机总数 * @return MachinesAll 云主机总数 */ public Long getMachinesAll() { return this.MachinesAll; } /** * Set 云主机总数 * @param MachinesAll 云主机总数 */ public void setMachinesAll(Long MachinesAll) { this.MachinesAll = MachinesAll; } /** * Get 云主机没有安装主机安全客户端的总数 * @return MachinesUninstalled 云主机没有安装主机安全客户端的总数 */ public Long getMachinesUninstalled() { return this.MachinesUninstalled; } /** * Set 云主机没有安装主机安全客户端的总数 * @param MachinesUninstalled 云主机没有安装主机安全客户端的总数 */ public void setMachinesUninstalled(Long MachinesUninstalled) { this.MachinesUninstalled = MachinesUninstalled; } /** * Get 主机安全客户端总数的总数 * @return AgentsAll 主机安全客户端总数的总数 */ public Long getAgentsAll() { return this.AgentsAll; } /** * Set 主机安全客户端总数的总数 * @param AgentsAll 主机安全客户端总数的总数 */ public void setAgentsAll(Long AgentsAll) { this.AgentsAll = AgentsAll; } /** * Get 主机安全客户端在线的总数 * @return AgentsOnline 主机安全客户端在线的总数 */ public Long getAgentsOnline() { return this.AgentsOnline; } /** * Set 主机安全客户端在线的总数 * @param AgentsOnline 主机安全客户端在线的总数 */ public void setAgentsOnline(Long AgentsOnline) { this.AgentsOnline = AgentsOnline; } /** * Get 主机安全客户端 离线+关机 的总数 * @return AgentsOffline 主机安全客户端 离线+关机 的总数 */ public Long getAgentsOffline() { return this.AgentsOffline; } /** * Set 主机安全客户端 离线+关机 的总数 * @param AgentsOffline 主机安全客户端 离线+关机 的总数 */ public void setAgentsOffline(Long AgentsOffline) { this.AgentsOffline = AgentsOffline; } /** * Get 主机安全客户端专业版的总数 * @return AgentsPro 主机安全客户端专业版的总数 */ public Long getAgentsPro() { return this.AgentsPro; } /** * Set 主机安全客户端专业版的总数 * @param AgentsPro 主机安全客户端专业版的总数 */ public void setAgentsPro(Long AgentsPro) { this.AgentsPro = AgentsPro; } /** * Get 主机安全客户端基础版的总数 * @return AgentsBasic 主机安全客户端基础版的总数 */ public Long getAgentsBasic() { return this.AgentsBasic; } /** * Set 主机安全客户端基础版的总数 * @param AgentsBasic 主机安全客户端基础版的总数 */ public void setAgentsBasic(Long AgentsBasic) { this.AgentsBasic = AgentsBasic; } /** * Get 7天内到期的预付费专业版总数 * @return AgentsProExpireWithInSevenDays 7天内到期的预付费专业版总数 */ public Long getAgentsProExpireWithInSevenDays() { return this.AgentsProExpireWithInSevenDays; } /** * Set 7天内到期的预付费专业版总数 * @param AgentsProExpireWithInSevenDays 7天内到期的预付费专业版总数 */ public void setAgentsProExpireWithInSevenDays(Long AgentsProExpireWithInSevenDays) { this.AgentsProExpireWithInSevenDays = AgentsProExpireWithInSevenDays; } /** * Get 风险主机总数 * @return RiskMachine 风险主机总数 */ public Long getRiskMachine() { return this.RiskMachine; } /** * Set 风险主机总数 * @param RiskMachine 风险主机总数 */ public void setRiskMachine(Long RiskMachine) { this.RiskMachine = RiskMachine; } /** * Get 已关机总数 * @return Shutdown 已关机总数 */ public Long getShutdown() { return this.Shutdown; } /** * Set 已关机总数 * @param Shutdown 已关机总数 */ public void setShutdown(Long Shutdown) { this.Shutdown = Shutdown; } /** * Get 已离线总数 * @return Offline 已离线总数 */ public Long getOffline() { return this.Offline; } /** * Set 已离线总数 * @param Offline 已离线总数 */ public void setOffline(Long Offline) { this.Offline = Offline; } /** * Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public String getRequestId() { return this.RequestId; } /** * Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public void setRequestId(String RequestId) { this.RequestId = RequestId; } public DescribeGeneralStatResponse() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public DescribeGeneralStatResponse(DescribeGeneralStatResponse source) { if (source.MachinesAll != null) { this.MachinesAll = new Long(source.MachinesAll); } if (source.MachinesUninstalled != null) { this.MachinesUninstalled = new Long(source.MachinesUninstalled); } if (source.AgentsAll != null) { this.AgentsAll = new Long(source.AgentsAll); } if (source.AgentsOnline != null) { this.AgentsOnline = new Long(source.AgentsOnline); } if (source.AgentsOffline != null) { this.AgentsOffline = new Long(source.AgentsOffline); } if (source.AgentsPro != null) { this.AgentsPro = new Long(source.AgentsPro); } if (source.AgentsBasic != null) { this.AgentsBasic = new Long(source.AgentsBasic); } if (source.AgentsProExpireWithInSevenDays != null) { this.AgentsProExpireWithInSevenDays = new Long(source.AgentsProExpireWithInSevenDays); } if (source.RiskMachine != null) { this.RiskMachine = new Long(source.RiskMachine); } if (source.Shutdown != null) { this.Shutdown = new Long(source.Shutdown); } if (source.Offline != null) { this.Offline = new Long(source.Offline); } if (source.RequestId != null) { this.RequestId = new String(source.RequestId); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "MachinesAll", this.MachinesAll); this.setParamSimple(map, prefix + "MachinesUninstalled", this.MachinesUninstalled); this.setParamSimple(map, prefix + "AgentsAll", this.AgentsAll); this.setParamSimple(map, prefix + "AgentsOnline", this.AgentsOnline); this.setParamSimple(map, prefix + "AgentsOffline", this.AgentsOffline); this.setParamSimple(map, prefix + "AgentsPro", this.AgentsPro); this.setParamSimple(map, prefix + "AgentsBasic", this.AgentsBasic); this.setParamSimple(map, prefix + "AgentsProExpireWithInSevenDays", this.AgentsProExpireWithInSevenDays); this.setParamSimple(map, prefix + "RiskMachine", this.RiskMachine); this.setParamSimple(map, prefix + "Shutdown", this.Shutdown); this.setParamSimple(map, prefix + "Offline", this.Offline); this.setParamSimple(map, prefix + "RequestId", this.RequestId); } }
/* * Copyright (C) 2009-2020 Lightbend Inc. <https://www.lightbend.com> */ package play.test; import org.junit.After; import org.junit.Before; /** * Provides a server and browser to JUnit tests. Make your test class extend this class and an * application, a server and a browser will be started before each test is invoked. You can setup * the fake application to use, the port and the browser to use by overriding the * provideApplication, providePort and provideBrowser methods, respectively. Within a test, the * running application, the TCP port and the browser are available through the app, port and browser * fields, respectively. */ public class WithBrowser extends WithServer { protected TestBrowser browser; /** * Override this if you want to use a different browser * * @param port the port to run the browser against. * @return a new test browser */ protected TestBrowser provideBrowser(int port) { return Helpers.testBrowser(port); } @Before public void createBrowser() { browser = provideBrowser(port); } @After public void quitBrowser() { if (browser != null) { browser.quit(); browser = null; } } }
package br.com.vvaug.ezlead.rest; import br.com.vvaug.ezlead.dto.LeadRequest; import br.com.vvaug.ezlead.dto.ProjectRequest; import br.com.vvaug.ezlead.dto.ProjectResponse; import br.com.vvaug.ezlead.service.ProjectService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.annotation.RequestScope; import org.springframework.web.servlet.ModelAndView; import java.util.List; import java.util.Map; import static org.springframework.http.HttpStatus.CREATED; import static org.springframework.http.HttpStatus.NO_CONTENT; @RequestMapping("/projects") @RestController @RequiredArgsConstructor @Slf4j public class ProjectController { private final ProjectService projectService; @GetMapping public List<ProjectResponse> findProjects(){ return projectService.findProjects(); } @PostMapping @ResponseStatus(CREATED) public ProjectResponse create(@RequestBody @Validated ProjectRequest projectRequest){ return projectService.create(projectRequest); } @PutMapping("/{id}") public ProjectResponse update(@PathVariable String id, @RequestBody ProjectRequest projectRequest){ return projectService.update(id, projectRequest); } @DeleteMapping("/{id}") @ResponseStatus(NO_CONTENT) public void delete(@PathVariable String id){ projectService.remove(id); } @PostMapping("/{id}/leads") @ResponseStatus(CREATED) public ProjectResponse addLead(@PathVariable String id, @RequestBody @Validated LeadRequest leadRequest){ return projectService.addLead(id, leadRequest); } @PutMapping("/{id}/leads/{leadId}") public ProjectResponse updateLead(@PathVariable("id") String projectId, @PathVariable("leadId") String leadId, @RequestBody LeadRequest leadRequest){ return projectService.updateLead(projectId, leadId, leadRequest); } }
package minesweeper.controllers; import gui.ButtonControllerFactoryInterface; import gui.UtilFrameListenerInterface; import minesweeper.GameSettings; import minesweeper.PlayersTurn; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Observable; import java.util.Observer; import java.util.function.BiPredicate; final class Locker { boolean hasChanged = false; } @SuppressWarnings("deprecation") public class SwingController implements ControllerInterface, Observer, ButtonControllerFactoryInterface, UtilFrameListenerInterface { private GameSettings bufferedSettings; private PlayersTurn bufferedTurn; private final Locker lockSettings = new Locker(); private final Locker lockTurn = new Locker(); @Override public ActionListener getListenerSettings(JSpinner sizeSpinner, JSpinner minesSpinner) { return e -> { int size = (int) sizeSpinner.getValue(); int mines = (int) minesSpinner.getValue(); bufferedSettings = new GameSettings(mines, size); synchronized (lockSettings) { lockSettings.hasChanged = true; lockSettings.notifyAll(); } }; } @Override public ActionListener getListenerExit() { return e -> { bufferedTurn = new PlayersTurn(0, 0, PlayersTurn.TurnTypes.EXIT); synchronized (lockTurn) { lockTurn.hasChanged = true; lockTurn.notifyAll(); } }; } @Override public ActionListener getListenerReset() { return e -> { bufferedTurn = new PlayersTurn(0, 0, PlayersTurn.TurnTypes.RESET); synchronized (lockTurn) { lockTurn.hasChanged = true; lockTurn.notifyAll(); } }; } class FiledTilesController extends Observable implements MouseListener { private final int x, y; FiledTilesController(int x, int y) { this.x = x; this.y = y; addObserver(SwingController.this); } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { JButton source = (JButton) e.getSource(); if (SwingUtilities.isRightMouseButton(e)) { source.getModel().setPressed(true); setChanged(); notifyObservers(new PlayersTurn(x, y, PlayersTurn.TurnTypes.MARK)); } else if (SwingUtilities.isLeftMouseButton(e)) { setChanged(); notifyObservers(new PlayersTurn(x, y, PlayersTurn.TurnTypes.OPEN)); } } @Override public void mouseReleased(MouseEvent e) { JButton source = (JButton) e.getSource(); source.getModel().setPressed(false); source.getModel().setArmed(true); } @Override public void mouseEntered(MouseEvent e) { JButton source = (JButton) e.getSource(); source.getModel().setArmed(true); } @Override public void mouseExited(MouseEvent e) { JButton source = (JButton) e.getSource(); source.getModel().setArmed(false); } } public FiledTilesController getController(int x, int y) { return new FiledTilesController(x, y); } @Override public GameSettings getSettings() throws InterruptedException { synchronized (lockSettings) { while(!lockSettings.hasChanged) { lockSettings.wait(); } lockSettings.hasChanged = false; } return bufferedSettings; } @Override public PlayersTurn getTurn(BiPredicate<Integer, Integer> correctCord) throws InterruptedException { synchronized (lockTurn) { while(!lockTurn.hasChanged) { lockTurn.wait(); } lockTurn.hasChanged = false; } return bufferedTurn; } @Override public void update(Observable o, Object arg) { if (o instanceof FiledTilesController) { bufferedTurn = (PlayersTurn) arg; } synchronized (lockTurn) { lockTurn.hasChanged = true; lockTurn.notifyAll(); } } }
package com.bx.erp.selenium.profile.commodity.HistoryR; import org.junit.Test; import org.junit.Before; import org.junit.After; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.core.IsNot.not; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Dimension; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Alert; import org.openqa.selenium.Keys; import java.util.*; public class UTR2commodityDetails2Test { private WebDriver driver; private Map<String, Object> vars; JavascriptExecutor js; @Before public void setUp() { driver = new ChromeDriver(); js = (JavascriptExecutor) driver; vars = new HashMap<String, Object>(); } @After public void tearDown() { driver.quit(); } public void LoginSucceed() { driver.get("https://localhost:8888/home/adminLogin.bx"); driver.manage().window().setSize(new Dimension(1920, 1040)); driver.findElement(By.name("companySN")).click(); driver.findElement(By.name("companySN")).sendKeys("668866"); driver.findElement(By.name("phone")).click(); driver.findElement(By.name("phone")).sendKeys("15854320895"); driver.findElement(By.name("pwdEncrypted")).click(); driver.findElement(By.name("pwdEncrypted")).sendKeys("000000"); driver.findElement(By.cssSelector(".layui-btn")).click(); } @Test public void uTR2commodityDetails2() { LoginSucceed(); driver.findElement(By.cssSelector(".layui-icon-app")).click(); driver.findElement(By.linkText("商品资料")).click(); driver.findElement(By.linkText("修改记录")).click(); driver.switchTo().frame(1); vars.put("historyCount", driver.findElement(By.cssSelector("#commodityHistoryList + div .layui-laypage-count")).getText()); // TODO // System.out.println("商品修改记录条数为:vars.get("historyCount").toString()"); driver.switchTo().defaultContent(); driver.findElement(By.linkText("商品列表")).click(); driver.switchTo().frame(2); driver.findElement(By.cssSelector(".layui-btn-sm:nth-child(1)")).click(); driver.findElement(By.name("barcodes")).click(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } driver.findElement(By.name("barcodes")).sendKeys("12346589"); vars.put("commodityName1", js.executeScript("return \"亢龙有悔\" + parseInt(Math.random()*1000);")); driver.findElement(By.cssSelector(".layui-form-item:nth-child(10)")).click(); driver.findElement(By.name("name")).click(); driver.findElement(By.name("name")).sendKeys(vars.get("commodityName1").toString()); driver.findElement(By.name("specification")).click(); driver.findElement(By.name("specification")).sendKeys("克"); driver.findElement(By.name("priceRetail")).click(); driver.findElement(By.name("priceRetail")).sendKeys("66.00"); driver.findElement(By.cssSelector(".btnChoosed")).click(); driver.findElement(By.linkText("确定")).click(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } assertThat(driver.findElement(By.cssSelector(".layui-layer-content")).getText(), is("创建商品成功")); driver.findElement(By.cssSelector(".layui-btn-sm:nth-child(1)")).click(); driver.findElement(By.name("barcodes")).click(); driver.findElement(By.name("barcodes")).sendKeys("12346589"); vars.put("commodityName2", js.executeScript("return \"亢龙有悔\" + parseInt(Math.random()*1000);")); driver.findElement(By.name("name")).click(); driver.findElement(By.name("name")).sendKeys(vars.get("commodityName2").toString()); driver.findElement(By.name("specification")).click(); driver.findElement(By.name("specification")).sendKeys("克"); driver.findElement(By.name("priceRetail")).click(); driver.findElement(By.name("priceRetail")).sendKeys("66.00"); driver.findElement(By.cssSelector(".btnChoosed")).click(); driver.findElement(By.linkText("确定")).click(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } assertThat(driver.findElement(By.cssSelector(".layui-layer-content")).getText(), is("创建商品成功")); // TODO // System.out.println("创建的商品名称1为:vars.get("commodityName1").toString()"); vars.put("historyCount", js.executeScript("function test(text){ var num = parseInt(text.replace(/[^0-9]/ig, \"\")); num += 4; text = \"共 \" + num + \" 条\"; return text; } return test(arguments[0]);", vars.get("historyCount"))); // TODO // System.out.println("此时应查到的商品修改记录条数为:vars.get("historyCount").toString()"); driver.switchTo().defaultContent(); driver.findElement(By.cssSelector("li:nth-child(2) > .layui-unselect")).click(); driver.findElement(By.linkText("修改记录")).click(); driver.switchTo().frame(2); assertThat(driver.findElement(By.cssSelector("#commodityHistoryList + div .layui-laypage-count")).getText(), is("vars.get(\"historyCount\").toString()")); driver.findElement(By.xpath("//div[@id=\'commodityHistoryMain\']/div[2]/div/div/div/div/div[2]/table/tbody/tr[3]/td/div")).click(); { String value = driver.findElement(By.name("name")).getAttribute("value"); // TODO // assertThat(value, is("vars.get("commodityName1").toString()")); } driver.close(); } }
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.spring; import com.hazelcast.nio.serialization.DataSerializableFactory; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; /** * @author asimarslan */ public class DummyDataSerializableFactory implements DataSerializableFactory { @Override public IdentifiedDataSerializable create(int typeId) { throw new UnsupportedOperationException("not implemented yet"); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.ecsops.transform.v20160401; import com.aliyuncs.ecsops.model.v20160401.OpsModifyDiagnosticPluginItemResponse; import com.aliyuncs.transform.UnmarshallerContext; public class OpsModifyDiagnosticPluginItemResponseUnmarshaller { public static OpsModifyDiagnosticPluginItemResponse unmarshall(OpsModifyDiagnosticPluginItemResponse opsModifyDiagnosticPluginItemResponse, UnmarshallerContext _ctx) { opsModifyDiagnosticPluginItemResponse.setRequestId(_ctx.stringValue("OpsModifyDiagnosticPluginItemResponse.RequestId")); opsModifyDiagnosticPluginItemResponse.setItemCode(_ctx.stringValue("OpsModifyDiagnosticPluginItemResponse.ItemCode")); return opsModifyDiagnosticPluginItemResponse; } }
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 4.0.0 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package xyz.redtorch.gateway.ctp.x64v6v5v1cpv.api; public class CThostFtdcQueryBrokerDepositField { private transient long swigCPtr; protected transient boolean swigCMemOwn; protected CThostFtdcQueryBrokerDepositField(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(CThostFtdcQueryBrokerDepositField obj) { return (obj == null) ? 0 : obj.swigCPtr; } @SuppressWarnings("deprecation") protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; jctpv6v5v1cpx64apiJNI.delete_CThostFtdcQueryBrokerDepositField(swigCPtr); } swigCPtr = 0; } } public void setBrokerID(String value) { jctpv6v5v1cpx64apiJNI.CThostFtdcQueryBrokerDepositField_BrokerID_set(swigCPtr, this, value); } public String getBrokerID() { return jctpv6v5v1cpx64apiJNI.CThostFtdcQueryBrokerDepositField_BrokerID_get(swigCPtr, this); } public void setExchangeID(String value) { jctpv6v5v1cpx64apiJNI.CThostFtdcQueryBrokerDepositField_ExchangeID_set(swigCPtr, this, value); } public String getExchangeID() { return jctpv6v5v1cpx64apiJNI.CThostFtdcQueryBrokerDepositField_ExchangeID_get(swigCPtr, this); } public CThostFtdcQueryBrokerDepositField() { this(jctpv6v5v1cpx64apiJNI.new_CThostFtdcQueryBrokerDepositField(), true); } }
package us.ihmc.commonWalkingControlModules.highLevelHumanoidControl.factories; import us.ihmc.commonWalkingControlModules.highLevelHumanoidControl.HighLevelControllerFactoryHelper; import us.ihmc.commonWalkingControlModules.highLevelHumanoidControl.highLevelStates.HighLevelControllerState; import us.ihmc.commonWalkingControlModules.highLevelHumanoidControl.highLevelStates.WalkingControllerState; import us.ihmc.humanoidRobotics.communication.packets.dataobjects.HighLevelControllerName; public class WalkingControllerStateFactory implements HighLevelControllerStateFactory { private WalkingControllerState walkingControllerState; @Override public HighLevelControllerState getOrCreateControllerState(HighLevelControllerFactoryHelper controllerFactoryHelper) { if (walkingControllerState == null) { walkingControllerState = new WalkingControllerState(controllerFactoryHelper.getCommandInputManager(), controllerFactoryHelper.getStatusMessageOutputManager(), controllerFactoryHelper.getManagerFactory(), controllerFactoryHelper.getHighLevelHumanoidControllerToolbox(), controllerFactoryHelper.getHighLevelControllerParameters(), controllerFactoryHelper.getWalkingControllerParameters()); } return walkingControllerState; } @Override public HighLevelControllerName getStateEnum() { return HighLevelControllerName.WALKING; } }
package io.invertase.firebase.fabric.crashlytics; import android.util.Log; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.crashlytics.android.Crashlytics; public class RNFirebaseCrashlytics extends ReactContextBaseJavaModule { private static final String TAG = "RNFirebaseCrashlytics"; public RNFirebaseCrashlytics(ReactApplicationContext reactContext) { super(reactContext); Log.d(TAG, "New instance"); } @Override public String getName() { return TAG; } @ReactMethod public void crash() { Crashlytics.getInstance().crash(); } @ReactMethod public void log(final String message) { Crashlytics.log(message); } @ReactMethod public void recordError(final int code, final String domain) { Crashlytics.logException(new Exception(code + ": " + domain)); } @ReactMethod public void setBoolValue(final String key, final boolean boolValue) { Crashlytics.setBool(key, boolValue); } @ReactMethod public void setFloatValue(final String key, final float floatValue) { Crashlytics.setFloat(key, floatValue); } @ReactMethod public void setIntValue(final String key, final int intValue) { Crashlytics.setInt(key, intValue); } @ReactMethod public void setStringValue(final String key, final String stringValue) { Crashlytics.setString(key, stringValue); } @ReactMethod public void setUserIdentifier(String userId) { Crashlytics.setUserIdentifier(userId); } }
/* WIEDZA * ----------------- * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ */ package org.wiedza.monitoring.api.exceptions; /** * Asserts * * @author patrickguillerm * @since 21 mars 2018 */ public final class Asserts { // ========================================================================= // CONSTRUCTORS // ========================================================================= private Asserts() { } // ========================================================================= // NULL / NOT NULL // ========================================================================= public static void isNull(final Object... values) { isNotNull(null, values); } public static void isNull(String msg, final Object... values) { for (final Object value : values) { if (value != null) { throw new IllegalArgumentException(msg == null ? "objects must be null!" : msg); } } } public static void isNotNull(final Object... values) { isNotNull(null, values); } public static void isNotNull(String msg, final Object... values) { for (final Object value : values) { if (value == null) { throw new IllegalArgumentException(msg == null ? "objects mustn't be null!" : msg); } } } }
package de0.coxthieving; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import javax.inject.Inject; import net.runelite.api.Client; import net.runelite.api.NPC; import net.runelite.api.Point; import net.runelite.client.ui.FontManager; import net.runelite.client.ui.overlay.Overlay; import net.runelite.client.ui.overlay.OverlayLayer; import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.OverlayUtil; public class ScavHighlight extends Overlay { private Client client; @Inject public ScavHighlight(CoxThievingPlugin plugin, Client client) { super(plugin); this.client = client; setPosition(OverlayPosition.DYNAMIC); setLayer(OverlayLayer.ABOVE_SCENE); } @Override public Dimension render(Graphics2D g) { NPC scav = null; for (NPC npc : client.getNpcs()) { if (npc == null) continue; if (npc.getId() == 7602 || npc.getId() == 7603) scav = npc; } if (scav == null) return null; g.setFont(FontManager.getRunescapeBoldFont()); String str; if (client.getVarbitValue(5424) == 1) { str = Integer.toString((scav.getHealthRatio() + 2) * 3 / 10); } else { str = scav.getHealthRatio() + "%"; } Point point = scav.getCanvasTextLocation(g, str, scav.getLogicalHeight()); if (point == null) return null; point = new Point(point.getX(), point.getY() + 20); OverlayUtil.renderTextLocation(g, point, str, Color.GREEN); return null; } }
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.migrationanalyzer.contributions.deploymentdescriptors; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.migrationanalyzer.analyze.fs.FileSystemEntry; import org.springframework.migrationanalyzer.analyze.support.AnalysisFailedException; import org.springframework.migrationanalyzer.analyze.support.EntryAnalyzer; import org.springframework.migrationanalyzer.util.IoUtils; final class DeploymentDescriptorDetectingEntryAnalyzer implements EntryAnalyzer<DeploymentDescriptor> { private static final String DETECTED_DEPLOYMENT_DESCRIPTORS_PROPERTIES_FILE_NAME = "org/springframework/migrationanalyzer/contributions/deploymentdescriptors/detected-deployment-descriptors.properties"; private final Map<String, String> deploymentDescriptorsToDetect; private final Logger logger = LoggerFactory.getLogger(DeploymentDescriptorDetectingEntryAnalyzer.class); DeploymentDescriptorDetectingEntryAnalyzer() { this.deploymentDescriptorsToDetect = buildDetectedDeploymentDescriptors(readDetectedDeploymentDescriptors(DETECTED_DEPLOYMENT_DESCRIPTORS_PROPERTIES_FILE_NAME)); } private Map<String, String> buildDetectedDeploymentDescriptors(Properties detectedDeploymentDescriptorsProperties) { Set<Object> keySet = detectedDeploymentDescriptorsProperties.keySet(); Map<String, String> descriptorsToDetect = new HashMap<String, String>(); for (Object object : keySet) { String descriptorCategory = (String) object; String descriptorFileNamesProperty = detectedDeploymentDescriptorsProperties.getProperty(descriptorCategory); String[] descriptorFileNames = descriptorFileNamesProperty.split(","); for (String descriptorFileName : descriptorFileNames) { descriptorsToDetect.put(descriptorFileName.trim(), descriptorCategory); } } return descriptorsToDetect; } private Properties readDetectedDeploymentDescriptors(String propertiesFileName) { Properties properties = new Properties(); InputStream inputStream = null; try { inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesFileName); properties.load(inputStream); } catch (IOException ioe) { this.logger.error("Failed to read " + propertiesFileName, ioe); } finally { IoUtils.closeQuietly(inputStream); } return properties; } @Override public Set<DeploymentDescriptor> analyze(FileSystemEntry fileSystemEntry) throws AnalysisFailedException { Set<DeploymentDescriptor> deploymentDescriptors = new HashSet<DeploymentDescriptor>(); String entryName = fileSystemEntry.getName(); if (entryName.contains("/")) { entryName = entryName.substring(entryName.lastIndexOf('/') + 1); } String descriptorCategory = this.deploymentDescriptorsToDetect.get(entryName); if (descriptorCategory != null) { deploymentDescriptors.add(new DeploymentDescriptor(descriptorCategory, fileSystemEntry, entryName)); } return deploymentDescriptors; } }
package com.hausontech.hrs.daoImpl.engine.thread; import java.util.*; public class ThreadPoolWorker extends Object { private static int nextWorkerID = 0; public ObjectFIFO idleWorkers; private int workerID; private ObjectFIFO handoffBox; private Thread internalThread; private volatile boolean noStopRequested; public ThreadPoolWorker(ObjectFIFO idleWorkers,ClassLoader cl) { this.idleWorkers = idleWorkers; workerID = getNextWorkerID(); handoffBox = new ObjectFIFO(1); // only one slot // just before returning, the thread should be created and started. noStopRequested = true; Runnable r = new Runnable() { public void run() { try { runWork(); } catch ( Exception x ) { // in case ANY exception slips through x.printStackTrace(); } } }; internalThread = new Thread(r); internalThread.setContextClassLoader(cl); internalThread.start(); } public ThreadPoolWorker(ObjectFIFO idleWorkers) { this.idleWorkers = idleWorkers; workerID = getNextWorkerID(); handoffBox = new ObjectFIFO(1); // only one slot // just before returning, the thread should be created and started. noStopRequested = true; Runnable r = new Runnable() { public void run() { try { runWork(); } catch ( Exception x ) { // in case ANY exception slips through x.printStackTrace(); } } }; internalThread = new Thread(r); internalThread.start(); } public static synchronized int getNextWorkerID() { // notice: synchronized at the class level to ensure uniqueness int id = nextWorkerID; nextWorkerID++; return id; } public void process(Runnable target) throws InterruptedException { handoffBox.add(target); } private void runWork() { while ( noStopRequested ) { try { // Worker is ready work. This will never block since the // idleWorker FIFO queue has enough capacity for all of // the workers. idleWorkers.add(this); // wait here until the server puts a request into the box Runnable r = (Runnable) handoffBox.remove(); runIt(r); // catches all exceptions } catch ( InterruptedException x ) { Thread.currentThread().interrupt(); // re-assert } } } private void runIt(Runnable r) { try { r.run(); } catch ( Exception runex ) { // catch any and all exceptions System.err.println("Uncaught exception fell through from run()"); runex.printStackTrace(); } finally { // Clear the interrupted flag (in case it comes back set) // so that if the loop goes again, the // handoffBox.remove() does not mistakenly throw // an InterruptedException. Thread.interrupted(); } } public void stopRequest() { noStopRequested = false; internalThread.interrupt(); } public boolean isAlive() { return internalThread.isAlive(); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/datalabeling/v1beta1/annotation.proto package com.google.cloud.datalabeling.v1beta1; public interface ImageBoundingPolyAnnotationOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.datalabeling.v1beta1.ImageBoundingPolyAnnotation) com.google.protobuf.MessageOrBuilder { /** * <code>.google.cloud.datalabeling.v1beta1.BoundingPoly bounding_poly = 2;</code> * @return Whether the boundingPoly field is set. */ boolean hasBoundingPoly(); /** * <code>.google.cloud.datalabeling.v1beta1.BoundingPoly bounding_poly = 2;</code> * @return The boundingPoly. */ com.google.cloud.datalabeling.v1beta1.BoundingPoly getBoundingPoly(); /** * <code>.google.cloud.datalabeling.v1beta1.BoundingPoly bounding_poly = 2;</code> */ com.google.cloud.datalabeling.v1beta1.BoundingPolyOrBuilder getBoundingPolyOrBuilder(); /** * <code>.google.cloud.datalabeling.v1beta1.NormalizedBoundingPoly normalized_bounding_poly = 3;</code> * @return Whether the normalizedBoundingPoly field is set. */ boolean hasNormalizedBoundingPoly(); /** * <code>.google.cloud.datalabeling.v1beta1.NormalizedBoundingPoly normalized_bounding_poly = 3;</code> * @return The normalizedBoundingPoly. */ com.google.cloud.datalabeling.v1beta1.NormalizedBoundingPoly getNormalizedBoundingPoly(); /** * <code>.google.cloud.datalabeling.v1beta1.NormalizedBoundingPoly normalized_bounding_poly = 3;</code> */ com.google.cloud.datalabeling.v1beta1.NormalizedBoundingPolyOrBuilder getNormalizedBoundingPolyOrBuilder(); /** * <pre> * Label of object in this bounding polygon. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.AnnotationSpec annotation_spec = 1;</code> * @return Whether the annotationSpec field is set. */ boolean hasAnnotationSpec(); /** * <pre> * Label of object in this bounding polygon. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.AnnotationSpec annotation_spec = 1;</code> * @return The annotationSpec. */ com.google.cloud.datalabeling.v1beta1.AnnotationSpec getAnnotationSpec(); /** * <pre> * Label of object in this bounding polygon. * </pre> * * <code>.google.cloud.datalabeling.v1beta1.AnnotationSpec annotation_spec = 1;</code> */ com.google.cloud.datalabeling.v1beta1.AnnotationSpecOrBuilder getAnnotationSpecOrBuilder(); public com.google.cloud.datalabeling.v1beta1.ImageBoundingPolyAnnotation.BoundedAreaCase getBoundedAreaCase(); }
package com.cargotracker.routing.domain.model.aggregates; import com.cargotracker.routing.domain.model.valueobjects.Schedule; import com.cargotracker.routing.domain.model.valueobjects.VoyageNumber; import javax.persistence.Entity; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Embedded; import javax.validation.constraints.NotNull; @Entity @NamedQueries({ @NamedQuery(name = "Voyage.findByVoyageNumber", query = "Select v from Voyage v where v.voyageNumber = :voyageNumber"), @NamedQuery(name = "Voyage.findAll", query = "Select v from Voyage v order by v.voyageNumber")}) public class Voyage { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Embedded @NotNull private Schedule schedule; @Embedded private VoyageNumber voyageNumber; public Voyage(){ } public Voyage(VoyageNumber voyageNumber,Schedule schedule){ this.schedule = schedule; this.voyageNumber = voyageNumber; } public VoyageNumber getVoyageNumber() { return voyageNumber; } public Schedule getSchedule() { return schedule; } }
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.syntax; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.events.Location; import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec; import com.google.devtools.build.lib.skylarkinterface.SkylarkModule; import com.google.devtools.build.lib.skylarkinterface.SkylarkPrinter; import com.google.devtools.build.lib.skylarkinterface.SkylarkValue; import java.util.List; import java.util.Objects; /** * An attribute value consisting of a concatenation of native types and selects, e.g: * * <pre> * rule( * name = 'myrule', * deps = * [':defaultdep'] * + select({ * 'a': [':adep'], * 'b': [':bdep'],}) * + select({ * 'c': [':cdep'], * 'd': [':ddep'],}) * ) * </pre> */ @SkylarkModule( name = "select", doc = "A selector between configuration-dependent entities.", documented = false ) @AutoCodec public final class SelectorList implements SkylarkValue { // TODO(build-team): Selectors are currently split between .packages and .syntax . They should // really all be in .packages, but then we'd need to figure out a way how to extend binary // operators, which is a non-trivial problem. private final Class<?> type; private final List<Object> elements; @AutoCodec.VisibleForSerialization SelectorList(Class<?> type, List<Object> elements) { this.type = type; this.elements = elements; } /** * Returns an ordered list of the elements in this expression. Each element may be a * native type or a select. */ public List<Object> getElements() { return elements; } /** * Returns the native type contained by this expression. */ public Class<?> getType() { return type; } /** * Creates a "wrapper" list that consists of a single select. */ public static SelectorList of(SelectorValue selector) { return new SelectorList(selector.getType(), ImmutableList.of(selector)); } /** * Creates a list that concatenates two values, where each value may be a native * type, a select over that type, or a selector list over that type. * * @throws EvalException if the values don't have the same underlying type */ public static SelectorList concat(Location location, Object value1, Object value2) throws EvalException { return of(location, value1, value2); } /** * Creates a list from the given sequence of values, which must be non-empty. Each value may be a * native type, a select over that type, or a selector list over that type. * * @throws EvalException if all values don't have the same underlying type */ public static SelectorList of(Location location, Object... values) throws EvalException { return SelectorList.of(location, ImmutableList.copyOf(values)); } /** * Creates a list from the given sequence of values, which must be non-empty. Each value may be a * native type, a select over that type, or a selector list over that type. * * @throws EvalException if all values don't have the same underlying type */ public static SelectorList of(Location location, Iterable<?> values) throws EvalException { Preconditions.checkArgument(!Iterables.isEmpty(values)); ImmutableList.Builder<Object> elements = ImmutableList.builder(); Object firstValue = null; for (Object value : values) { if (value instanceof SelectorList) { elements.addAll(((SelectorList) value).getElements()); } else { elements.add(value); } if (firstValue == null) { firstValue = value; } if (!canConcatenate(getNativeType(firstValue), getNativeType(value))) { throw new EvalException( location, String.format( "'+' operator applied to incompatible types (%s, %s)", EvalUtils.getDataTypeName(firstValue, true), EvalUtils.getDataTypeName(value, true))); } } return new SelectorList(getNativeType(firstValue), elements.build()); } private static final Class<?> NATIVE_LIST_TYPE = List.class; private static Class<?> getNativeType(Object value) { if (value instanceof SelectorList) { return ((SelectorList) value).getType(); } else if (value instanceof SelectorValue) { return ((SelectorValue) value).getType(); } else { return value.getClass(); } } private static boolean isListType(Class<?> type) { return NATIVE_LIST_TYPE.isAssignableFrom(type) || type.getSuperclass() == SkylarkList.class || type == GlobList.class; } private static boolean canConcatenate(Class<?> type1, Class<?> type2) { if (type1 == type2) { return true; } else if (isListType(type1) && isListType(type2)) { return true; } else { return false; } } @Override public String toString() { return Printer.repr(this); } @Override public void repr(SkylarkPrinter printer) { printer.printList(elements, "", " + ", "", null); } @Override public int hashCode() { return Objects.hash(type, elements); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof SelectorList)) { return false; } SelectorList that = (SelectorList) other; return Objects.equals(this.type, that.type) && Objects.equals(this.elements, that.elements); } }
package com.SAM2018.model; /** * ViewModel-like class that returns a complex dataset when a view needs connected data across multiple objects * Used when a Submitter views a report generated for their paper * @author <a href='mailto:add5980@rit.edu'>Andrew DiStasi</a> */ public class SubmissionReportDisplay { //Attributes public Paper paper; public Report report; /** * Parameterized Constructor for the class * @param _paper The Paper that a report was generated for * @param _report The report generated for the Paper */ public SubmissionReportDisplay(Paper _paper, Report _report) { this.paper = _paper; this.report = _report; } /** * Accessor for paper Attribute * @return paper The Paper that a report was generated for */ public Paper getPaper() { return paper; } /** * Accessor for report * @return report The report that was generated for the paper */ public Report getReport() { return report; } }
package com.example.coolweather.db; import org.litepal.crud.DataSupport; public class City extends DataSupport { private int Id; private String cityName; private int cityCode; private int provinceId; public int getId() { return Id; } public void setId(int id) { Id = id; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public int getCityCode() { return cityCode; } public void setCityCode(int cityCode) { this.cityCode = cityCode; } public int getProvinceId() { return provinceId; } public void setProvinceId(int provinceId) { this.provinceId = provinceId; } }
package ru.job4j.domain; import javax.persistence.*; @Entity @Table(name="motor") public class Motor { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Integer id; @Column (name = "name") private String name; public Motor() { } public Motor(Integer id) { this.id = id; } public Motor(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return String.format("{\"%s\" : \"%s\", \"%s\" : \"%s\"}", "id", id, "name", name); } }
package com.spring.basics; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import com.spring.basics.data.exporter.DataExporter; import com.spring.basics.dto.Salary; import com.spring.basics.model.service.DepartmentService; import com.spring.basics.model.service.EmployeeService; @Component public class ConsoleApplication implements CommandLineRunner{ @Autowired private DataExporter dataExporter; @Autowired private EmployeeService employeeService; @Autowired private DepartmentService departmentService; @Autowired private ApplicationContext applicationContext; public void run(String... args) throws Exception { Salary salary2 = applicationContext.getBean("salary", Salary.class); salary2.setValue(15000); salary2.setCreateDate(new Date()); System.out.println(salary2); Salary salary1 = applicationContext.getBean("salary", Salary.class); salary1.setValue(20000); salary1.setCreateDate(new Date()); System.out.println(salary1); String json = dataExporter.convertSalaryToJson(salary1); System.out.println(json); json = dataExporter.convertSalaryToJson(salary2); System.out.println(json); System.out.println("Çalışan Listesi"); System.out.println(employeeService.getAll()); System.out.println("Departman Listesi"); System.out.println(departmentService.getAll()); } public void sayHello() { System.out.println("Hello from ConsoleApplication!"); } }
package org.jeecg.boot.starter.redis.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.jeecg.boot.starter.redis.prop.JeecgRedisProperties; import org.jeecg.boot.starter.redis.service.RedisReceiver; import org.jeecg.common.constant.GlobalConstants; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.listener.ChannelTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * redis配置 * * @author jeecg */ @Slf4j @Configuration @EnableConfigurationProperties(JeecgRedisProperties.class) @ConditionalOnProperty(value = "spring.redis.enabled", havingValue = "true", matchIfMissing = true) public class RedisConfiguration { /** * RedisTemplate配置 * * @param lettuceConnectionFactory * @return */ @Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { log.info(" --- redis config init --- "); // 设置序列化 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置redisTemplate RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); redisTemplate.setConnectionFactory(lettuceConnectionFactory); RedisSerializer<?> stringSerializer = new StringRedisSerializer(); redisTemplate.setKeySerializer(stringSerializer);// key序列化 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// value序列化 redisTemplate.setHashKeySerializer(stringSerializer);// Hash key序列化 redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);// Hash value序列化 redisTemplate.afterPropertiesSet(); return redisTemplate; } /** * redis 监听配置 * * @param redisConnectionFactory redis 配置 * @return */ @Bean public RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory, RedisReceiver redisReceiver, MessageListenerAdapter commonListenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(redisConnectionFactory); container.addMessageListener(commonListenerAdapter, new ChannelTopic(GlobalConstants.REDIS_TOPIC_NAME)); return container; } @Bean MessageListenerAdapter commonListenerAdapter(RedisReceiver redisReceiver) { MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(redisReceiver, "onMessage"); messageListenerAdapter.setSerializer(jacksonSerializer()); return messageListenerAdapter; } private Jackson2JsonRedisSerializer jacksonSerializer() { Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); return jackson2JsonRedisSerializer; } }
/* * 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 cloud.erda.agent.plugin.shardingsphere.v4; import cloud.erda.agent.core.utils.Constants; import org.apache.skywalking.apm.agent.core.plugin.interceptor.context.IMethodInterceptContext; import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult; import cloud.erda.agent.core.tracing.Scope; import cloud.erda.agent.core.tracing.TracerManager; import cloud.erda.agent.core.tracing.TracerSnapshot; import cloud.erda.agent.core.tracing.span.Span; import cloud.erda.agent.core.utils.TracerUtils; import cloud.erda.agent.plugin.app.insight.transaction.TransactionMetricBuilder; import cloud.erda.agent.plugin.app.insight.MetricReporter; import cloud.erda.agent.plugin.app.insight.transaction.TransactionMetricUtils; import org.apache.shardingsphere.core.execute.ShardingExecuteDataMap; import java.util.Map; /** * {@link ExecuteInterceptor} enhances {@link org.apache.shardingsphere.core.execute.sql.execute.SQLExecuteCallback}, * creating a local span that records the execution of sql. */ public class ExecuteInterceptor implements InstanceMethodsAroundInterceptor { @Override public void beforeMethod(IMethodInterceptContext context, MethodInterceptResult result) throws Throwable { Object data = ShardingExecuteDataMap.getDataMap().remove(Constant.TRACER_SNAPSHOT); if (!(data instanceof TracerSnapshot)) { Object[] args = context.getArguments(); if (args != null && args.length >= 3 && args[2] instanceof Map) { data = ((Map) args[2]).remove(Constant.TRACER_SNAPSHOT); } } if (!(data instanceof TracerSnapshot)) { return; } TracerSnapshot snapshot = (TracerSnapshot) data; Span span = TracerManager.currentTracer().attach(snapshot).span(); String statement = span.getTags().get(Constants.Tags.DB_STATEMENT); TransactionMetricBuilder transactionMetricBuilder = new TransactionMetricBuilder(Constants.Metrics.APPLICATION_DB, false); context.setAttachment(Constants.Keys.METRIC_BUILDER, transactionMetricBuilder); transactionMetricBuilder.tag(Constants.Tags.COMPONENT, Constants.Tags.COMPONENT_SHARDING_SPHERE) .tag(Constants.Tags.SPAN_KIND, Constants.Tags.SPAN_KIND_CLIENT) .tag(Constants.Tags.DB_STATEMENT, statement); } @Override public Object afterMethod(IMethodInterceptContext context, Object ret) throws Throwable { TransactionMetricBuilder transactionMetricBuilder = context.getAttachment(Constants.Keys.METRIC_BUILDER); if (transactionMetricBuilder != null) { MetricReporter.report(transactionMetricBuilder); } Scope scope = TracerManager.currentTracer().active(); if (scope != null) { scope.close(); } return ret; } @Override public void handleMethodException(IMethodInterceptContext context, Throwable t) { TransactionMetricUtils.handleException(context); TracerUtils.handleException(t); } }
package com.thinkaurelius.titan.util.encoding; import com.google.common.base.Preconditions; /** * Utility class for encoding longs in strings based on: * {@linktourl http://stackoverflow.com/questions/2938482/encode-decode-a-long-to-a-string-using-a-fixed-set-of-letters-in-java} * * @author http://stackoverflow.com/users/276101/polygenelubricants * @author Matthias Broecheler (me@matthiasb.com) */ public class LongEncoding { private static final String BASE_SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyz"; public static long decode(String s) { return decode(s,BASE_SYMBOLS); } public static String encode(long num) { return encode(num,BASE_SYMBOLS); } public static long decode(String s, String symbols) { final int B = symbols.length(); long num = 0; for (char ch : s.toCharArray()) { num *= B; int pos = symbols.indexOf(ch); if (pos<0) throw new NumberFormatException("Symbol set does not match string"); num += pos; } return num; } public static String encode(long num, String symbols) { Preconditions.checkArgument(num>=0,"Expected non-negative number: " + num); final int B = symbols.length(); StringBuilder sb = new StringBuilder(); while (num != 0) { sb.append(symbols.charAt((int) (num % B))); num /= B; } return sb.reverse().toString(); } }
/******************************************************************************* * Copyright 2017 Bstek * * 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.bstek.uflo.deploy.validate; /** * @author Jacky.gao * @since 2013年11月29日 */ public class ProcessValidateException extends RuntimeException { private static final long serialVersionUID = -8700678017516761037L; private String message; public ProcessValidateException(String message){ this.message=message; } public String getMessage() { return message; } }
/* * Copyright 2016 Netflix, 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.netflix.metacat.common.server.spi; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.netflix.metacat.common.QualifiedName; import com.netflix.metacat.common.server.connectors.model.CatalogInfo; import com.netflix.metacat.common.server.connectors.model.ClusterInfo; import lombok.Getter; import java.util.Collections; import java.util.List; import java.util.Map; /** * Catalog config. */ @Getter public final class MetacatCatalogConfig { private static final Splitter COMMA_LIST_SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings(); private final boolean includeViewsWithTables; private final List<String> schemaBlacklist; private final List<String> schemaWhitelist; private final int thriftPort; private final String type; private final String catalogName; private final ClusterInfo clusterInfo; private MetacatCatalogConfig( final String type, final String catalogName, final ClusterInfo clusterInfo, final boolean includeViewsWithTables, final List<String> schemaWhitelist, final List<String> schemaBlacklist, final int thriftPort) { this.type = type; this.catalogName = catalogName; this.clusterInfo = clusterInfo; this.includeViewsWithTables = includeViewsWithTables; this.schemaBlacklist = schemaBlacklist; this.schemaWhitelist = schemaWhitelist; this.thriftPort = thriftPort; } /** * Creates the config. * * @param type type * @param catalogName catalog name * @param properties properties * @return config */ public static MetacatCatalogConfig createFromMapAndRemoveProperties( final String type, final String catalogName, final Map<String, String> properties) { Preconditions.checkArgument(!Strings.isNullOrEmpty(type), "type is required"); final String catalogType = properties.containsKey(Keys.CATALOG_TYPE) ? properties.remove(Keys.CATALOG_TYPE) : type; final List<String> schemaWhitelist = properties.containsKey(Keys.SCHEMA_WHITELIST) ? COMMA_LIST_SPLITTER.splitToList(properties.remove(Keys.SCHEMA_WHITELIST)) : Collections.EMPTY_LIST; final List<String> schemaBlacklist = properties.containsKey(Keys.SCHEMA_BLACKLIST) ? COMMA_LIST_SPLITTER.splitToList(properties.remove(Keys.SCHEMA_BLACKLIST)) : Collections.EMPTY_LIST; final boolean includeViewsWithTables = Boolean.parseBoolean(properties.remove(Keys.INCLUDE_VIEWS_WITH_TABLES)); int thriftPort = 0; if (properties.containsKey(Keys.THRIFT_PORT)) { thriftPort = Integer.parseInt(properties.remove(Keys.THRIFT_PORT)); } // Cluster information final String clusterName = properties.get(Keys.CLUSTER_NAME); final String clusterAccount = properties.get(Keys.CLUSTER_ACCOUNT); final String clusterAccountId = properties.get(Keys.CLUSTER_ACCOUNT_ID); final String clusterEnv = properties.get(Keys.CLUSTER_ENV); final String clusterRegion = properties.get(Keys.CLUSTER_REGION); final ClusterInfo clusterInfo = new ClusterInfo(clusterName, type, clusterAccount, clusterAccountId, clusterEnv, clusterRegion); return new MetacatCatalogConfig(catalogType, catalogName, clusterInfo, includeViewsWithTables, schemaWhitelist, schemaBlacklist, thriftPort); } public boolean isThriftInterfaceRequested() { return thriftPort != 0; } /** * Returns true if catalog is a proxy one. * @return Returns true if catalog is a proxy one. */ public boolean isProxy() { return type.equalsIgnoreCase("proxy"); } /** * Creates the catalog info. * @return catalog info */ public CatalogInfo toCatalogInfo() { return CatalogInfo.builder().name(QualifiedName.ofCatalog(catalogName)).clusterInfo(clusterInfo).build(); } /** * Properties in the catalog. */ public static class Keys { /** * Catalog name. Usually catalog name is derived from the name of the catalog properties file. * One could also specify it in the properties under the property name <code>catalog.name</code>. * For example, if a catalog has two shards with catalog defined in two property files, * then we can have the <code>catalog.name</code> set to one name. */ public static final String CATALOG_NAME = "catalog.name"; /** * Connector type. */ public static final String CONNECTOR_NAME = "connector.name"; /** * Catalog type. */ public static final String CATALOG_TYPE = "metacat.type"; /** * List views with tables. */ public static final String INCLUDE_VIEWS_WITH_TABLES = "metacat.schema.list-views-with-tables"; /** * Schemas that are black listed. */ public static final String SCHEMA_BLACKLIST = "metacat.schema.blacklist"; /** * Schemas that are white listed. */ public static final String SCHEMA_WHITELIST = "metacat.schema.whitelist"; /** * Thrift port. */ public static final String THRIFT_PORT = "metacat.thrift.port"; /** * Cluster name. */ public static final String CLUSTER_NAME = "metacat.cluster.name"; /** * Cluster account. */ public static final String CLUSTER_ACCOUNT = "metacat.cluster.account"; /** * Cluster account id. */ public static final String CLUSTER_ACCOUNT_ID = "metacat.cluster.account-id"; /** * Cluster region. */ public static final String CLUSTER_REGION = "metacat.cluster.region"; /** * Cluster environment. */ public static final String CLUSTER_ENV = "metacat.cluster.env"; } }
package com.github.lol.pay.component.unionpay.product.qrcode.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * qr code cancel consume sync response * * @author: jifuwei * @create: 2019-07-19 18:05 **/ @Data @NoArgsConstructor @AllArgsConstructor @Builder public class QRCodeCancelConsumeSyncResp implements Serializable { private static final long serialVersionUID = -691639620210914011L; private String queryId; private String signature; private String signMethod; private String respCode; private String respMsg; private String accInsCode; private String signPubKeyCert; private String origQryId; private String version; private String encoding; private String bizType; private String txnTime; private String txnAmt; private String txnType; private String txnSubType; private String accessType; private String reqReserved; private String merId; private String orderId; private String reserved; }
/********************************************************************************* * * * The MIT License (MIT) * * * * Copyright (c) 2015-2021 aoju.org and other contributors. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * * THE SOFTWARE. * * * ********************************************************************************/ package org.aoju.bus.image.nimble.opencv; import org.aoju.bus.image.nimble.codec.ImageDescriptor; import java.io.File; /** * @author Kimi Liu * @version 6.2.3 * @since JDK 1.8+ */ public class ExtendInputImageStream { private final File file; private final long[] segmentPositions; private final long[] segmentLengths; private final ImageDescriptor imageDescriptor; public ExtendInputImageStream(File file, long[] segmentPositions, int[] segmentLengths, ImageDescriptor imageDescriptor) { this.file = file; this.segmentPositions = segmentPositions; this.segmentLengths = null == segmentLengths ? null : getDoubleArray(segmentLengths); this.imageDescriptor = imageDescriptor; } public static double[] getDoubleArray(long[] array) { double[] a = new double[array.length]; for (int i = 0; i < a.length; i++) { a[i] = array[i]; } return a; } public static long[] getDoubleArray(int[] array) { long[] a = new long[array.length]; for (int i = 0; i < a.length; i++) { a[i] = array[i]; } return a; } public long[] getSegmentPositions() { return segmentPositions; } public long[] getSegmentLengths() { return segmentLengths; } public File getFile() { return file; } public ImageDescriptor getImageDescriptor() { return imageDescriptor; } }
package org.bouncycastle.tls.test; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.net.Socket; import java.security.SecureRandom; import java.util.Vector; import org.bouncycastle.tls.AlertDescription; import org.bouncycastle.tls.AlertLevel; import org.bouncycastle.tls.DefaultTlsClient; import org.bouncycastle.tls.HashAlgorithm; import org.bouncycastle.tls.ServerOnlyTlsAuthentication; import org.bouncycastle.tls.SignatureAlgorithm; import org.bouncycastle.tls.SignatureAndHashAlgorithm; import org.bouncycastle.tls.TlsAuthentication; import org.bouncycastle.tls.TlsClientProtocol; import org.bouncycastle.tls.TlsServerCertificate; import org.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import junit.framework.TestCase; import junit.framework.TestSuite; public class BasicTlsTest extends TestCase { private static final int PORT_NO = 12001; protected boolean isSufficientVMVersion(String vmVersion) { if (vmVersion == null) { return false; } String[] parts = vmVersion.split("\\."); if (parts == null || parts.length < 1) { return false; } try { int major = Integer.parseInt(parts[0]); if (major != 1) { return major > 1; } if (parts.length < 2) { return false; } int minor = Integer.parseInt(parts[1]); return minor >= 7; } catch (NumberFormatException e) { return false; } } public void testConnection() throws Exception { String vmVersion = System.getProperty("java.specification.version"); if (!isSufficientVMVersion(vmVersion)) { return; // only works on later VMs. } Thread server = new HTTPSServerThread(); server.start(); Thread.yield(); Socket s = null; for (int i = 0; s == null && i != 3; i++) { Thread.sleep(1000); try { s = new Socket("localhost", PORT_NO); } catch (IOException e) { // ignore } } if (s == null) { throw new IOException("unable to connect"); } TlsClientProtocol protocol = new TlsClientProtocol(s.getInputStream(), s.getOutputStream()); protocol.connect(new MyTlsClient(new ServerOnlyTlsAuthentication() { public void notifyServerCertificate(TlsServerCertificate serverCertificate) throws IOException { // NOTE: In production code this MUST verify the certificate! } })); InputStream is = protocol.getInputStream(); OutputStream os = protocol.getOutputStream(); os.write("GET / HTTP/1.1\r\n\r\n".getBytes()); byte[] buf = new byte[4096]; int read = 0; int total = 0; while ((read = is.read(buf, total, buf.length - total)) > 0) { total += read; } is.close(); byte[] expected = Hex.decode("485454502f312e3120323030204f4b0d0a436f6e74656e742d547970653a20746578742f68" + "746d6c0d0a0d0a3c68746d6c3e0d0a3c626f64793e0d0a48656c6c6f20576f726c64210d0a3c2f626f64793e0d0a3c2f" + "68746d6c3e0d0a"); assertEquals(total, expected.length); byte[] tmp = new byte[expected.length]; System.arraycopy(buf, 0, tmp, 0, total); assertTrue(Arrays.areEqual(expected, tmp)); } public static TestSuite suite() { return new TestSuite(BasicTlsTest.class); } public static void main(String[] args) throws Exception { junit.textui.TestRunner.run(suite()); } static class MyTlsClient extends DefaultTlsClient { public void notifyAlertRaised(short alertLevel, short alertDescription, String message, Throwable cause) { PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out; out.println("TLS client raised alert: " + AlertLevel.getText(alertLevel) + ", " + AlertDescription.getText(alertDescription)); if (message != null) { out.println("> " + message); } if (cause != null) { cause.printStackTrace(out); } } public void notifyAlertReceived(short alertLevel, short alertDescription) { PrintStream out = (alertLevel == AlertLevel.fatal) ? System.err : System.out; out.println("TLS client received alert: " + AlertLevel.getText(alertLevel) + ", " + AlertDescription.getText(alertDescription)); } private final TlsAuthentication authentication; MyTlsClient(TlsAuthentication authentication) { super(new BcTlsCrypto(new SecureRandom())); this.authentication = authentication; this.supportedSignatureAlgorithms = new Vector(); this.supportedSignatureAlgorithms.addElement(new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa)); this.supportedSignatureAlgorithms.addElement(new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa)); this.supportedSignatureAlgorithms.addElement(new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.rsa)); } public TlsAuthentication getAuthentication() throws IOException { return authentication; } } }
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.cpp; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.collect.nestedset.Order; import com.google.devtools.build.lib.util.Preconditions; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * A structured representation of the compilation outputs of a C++ rule. */ public class CcCompilationOutputs { /** * All .o files built by the target. */ private final ImmutableList<Artifact> objectFiles; /** * All .pic.o files built by the target. */ private final ImmutableList<Artifact> picObjectFiles; /** * All .o files coming from a C(++) compilation under our control. */ private final ImmutableList<Artifact> ltoBitcodeFiles; /** * All .dwo files built by the target, corresponding to .o outputs. */ private final ImmutableList<Artifact> dwoFiles; /** * All .pic.dwo files built by the target, corresponding to .pic.o outputs. */ private final ImmutableList<Artifact> picDwoFiles; /** * All artifacts that are created if "--save_temps" is true. */ private final NestedSet<Artifact> temps; /** * All token .h.processed files created when preprocessing or parsing headers. */ private final ImmutableList<Artifact> headerTokenFiles; private final List<IncludeScannable> lipoScannables; private CcCompilationOutputs( ImmutableList<Artifact> objectFiles, ImmutableList<Artifact> picObjectFiles, ImmutableList<Artifact> ltoBitcodeFiles, ImmutableList<Artifact> dwoFiles, ImmutableList<Artifact> picDwoFiles, NestedSet<Artifact> temps, ImmutableList<Artifact> headerTokenFiles, ImmutableList<IncludeScannable> lipoScannables) { this.objectFiles = objectFiles; this.picObjectFiles = picObjectFiles; this.ltoBitcodeFiles = ltoBitcodeFiles; this.dwoFiles = dwoFiles; this.picDwoFiles = picDwoFiles; this.temps = temps; this.headerTokenFiles = headerTokenFiles; this.lipoScannables = lipoScannables; } /** * Returns whether this set of outputs has any object or .pic object files. */ public boolean isEmpty() { return picObjectFiles.isEmpty() && objectFiles.isEmpty(); } /** * Returns an unmodifiable view of the .o or .pic.o files set. * * @param usePic whether to return .pic.o files */ public ImmutableList<Artifact> getObjectFiles(boolean usePic) { return usePic ? picObjectFiles : objectFiles; } /** * Returns unmodifiable view of object files resulting from compilation. */ public ImmutableList<Artifact> getLtoBitcodeFiles() { return ltoBitcodeFiles; } /** * Returns an unmodifiable view of the .dwo files set. */ public ImmutableList<Artifact> getDwoFiles() { return dwoFiles; } /** * Returns an unmodifiable view of the .pic.dwo files set. */ public ImmutableList<Artifact> getPicDwoFiles() { return picDwoFiles; } /** * Returns an unmodifiable view of the temp files set. */ public NestedSet<Artifact> getTemps() { return temps; } /** * Returns an unmodifiable view of the .h.processed files. */ public Iterable<Artifact> getHeaderTokenFiles() { return headerTokenFiles; } /** * Returns the {@link IncludeScannable} objects this C++ compile action contributes to a * LIPO context collector. */ public List<IncludeScannable> getLipoScannables() { return lipoScannables; } /** * Returns the output files that are considered "compiled" by this C++ compile action. */ NestedSet<Artifact> getFilesToCompile( boolean isLipoContextCollector, boolean parseHeaders, boolean usePic) { if (isLipoContextCollector) { return NestedSetBuilder.<Artifact>emptySet(Order.STABLE_ORDER); } NestedSetBuilder<Artifact> files = NestedSetBuilder.stableOrder(); files.addAll(getObjectFiles(usePic)); if (parseHeaders) { files.addAll(getHeaderTokenFiles()); } return files.build(); } public static final class Builder { private final Set<Artifact> objectFiles = new LinkedHashSet<>(); private final Set<Artifact> picObjectFiles = new LinkedHashSet<>(); private final Set<Artifact> ltoBitcodeFiles = new LinkedHashSet<>(); private final Set<Artifact> dwoFiles = new LinkedHashSet<>(); private final Set<Artifact> picDwoFiles = new LinkedHashSet<>(); private final NestedSetBuilder<Artifact> temps = NestedSetBuilder.stableOrder(); private final Set<Artifact> headerTokenFiles = new LinkedHashSet<>(); private final List<IncludeScannable> lipoScannables = new ArrayList<>(); public CcCompilationOutputs build() { return new CcCompilationOutputs( ImmutableList.copyOf(objectFiles), ImmutableList.copyOf(picObjectFiles), ImmutableList.copyOf(ltoBitcodeFiles), ImmutableList.copyOf(dwoFiles), ImmutableList.copyOf(picDwoFiles), temps.build(), ImmutableList.copyOf(headerTokenFiles), ImmutableList.copyOf(lipoScannables)); } public Builder merge(CcCompilationOutputs outputs) { this.objectFiles.addAll(outputs.objectFiles); this.picObjectFiles.addAll(outputs.picObjectFiles); this.dwoFiles.addAll(outputs.dwoFiles); this.picDwoFiles.addAll(outputs.picDwoFiles); this.temps.addTransitive(outputs.temps); this.headerTokenFiles.addAll(outputs.headerTokenFiles); this.lipoScannables.addAll(outputs.lipoScannables); return this; } /** * Adds an .o file. */ public Builder addObjectFile(Artifact artifact) { // We skip file extension checks for TreeArtifacts because they represent directory artifacts // without a file extension. Preconditions.checkArgument( artifact.isTreeArtifact() || Link.OBJECT_FILETYPES.matches(artifact.getFilename())); objectFiles.add(artifact); return this; } public Builder addObjectFiles(Iterable<Artifact> artifacts) { for (Artifact artifact : artifacts) { Preconditions.checkArgument(Link.OBJECT_FILETYPES.matches(artifact.getFilename())); } Iterables.addAll(objectFiles, artifacts); return this; } /** * Adds a .pic.o file. */ public Builder addPicObjectFile(Artifact artifact) { picObjectFiles.add(artifact); return this; } public Builder addLTOBitcodeFile(Artifact a) { ltoBitcodeFiles.add(a); return this; } public Builder addLTOBitcodeFile(Iterable<Artifact> artifacts) { Iterables.addAll(ltoBitcodeFiles, artifacts); return this; } public Builder addPicObjectFiles(Iterable<Artifact> artifacts) { for (Artifact artifact : artifacts) { Preconditions.checkArgument(Link.OBJECT_FILETYPES.matches(artifact.getFilename())); } Iterables.addAll(picObjectFiles, artifacts); return this; } public Builder addDwoFile(Artifact artifact) { dwoFiles.add(artifact); return this; } public Builder addPicDwoFile(Artifact artifact) { picDwoFiles.add(artifact); return this; } /** * Adds temp files. */ public Builder addTemps(Iterable<Artifact> artifacts) { temps.addAll(artifacts); return this; } public Builder addHeaderTokenFile(Artifact artifact) { headerTokenFiles.add(artifact); return this; } /** * Adds an {@link IncludeScannable} that this compilation output object contributes to a * LIPO context collector. */ public Builder addLipoScannable(IncludeScannable scannable) { lipoScannables.add(scannable); return this; } } }
/* * Copyright 2011-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 com.amazonaws.services.kinesisfirehose.model.transform; import java.util.Map; import java.util.List; import com.amazonaws.AmazonClientException; import com.amazonaws.services.kinesisfirehose.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.protocol.json.*; /** * CopyCommandMarshaller */ public class CopyCommandJsonMarshaller { /** * Marshall the given parameter object, and output to a SdkJsonGenerator */ public void marshall(CopyCommand copyCommand, StructuredJsonGenerator jsonGenerator) { if (copyCommand == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } try { jsonGenerator.writeStartObject(); if (copyCommand.getDataTableName() != null) { jsonGenerator.writeFieldName("DataTableName").writeValue(copyCommand.getDataTableName()); } if (copyCommand.getDataTableColumns() != null) { jsonGenerator.writeFieldName("DataTableColumns").writeValue(copyCommand.getDataTableColumns()); } if (copyCommand.getCopyOptions() != null) { jsonGenerator.writeFieldName("CopyOptions").writeValue(copyCommand.getCopyOptions()); } jsonGenerator.writeEndObject(); } catch (Throwable t) { throw new AmazonClientException("Unable to marshall request to JSON: " + t.getMessage(), t); } } private static CopyCommandJsonMarshaller instance; public static CopyCommandJsonMarshaller getInstance() { if (instance == null) instance = new CopyCommandJsonMarshaller(); return instance; } }
package com.nightlycommit.idea.twigextendedplugin.dic.linemarker; import com.intellij.codeInsight.daemon.LineMarkerInfo; import com.intellij.codeInsight.daemon.LineMarkerProvider; import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder; import com.intellij.patterns.XmlPatterns; import com.intellij.patterns.XmlTagPattern; import com.intellij.psi.PsiElement; import com.intellij.psi.xml.XmlTag; import com.nightlycommit.idea.twigextendedplugin.Symfony2ProjectComponent; import com.nightlycommit.idea.twigextendedplugin.util.dict.ServiceUtil; import com.nightlycommit.idea.twigextendedplugin.Symfony2ProjectComponent; import com.nightlycommit.idea.twigextendedplugin.config.xml.XmlHelper; import com.nightlycommit.idea.twigextendedplugin.util.dict.ServiceUtil; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; /** * @author Daniel Espendiller <daniel@espendiller.net> */ public class XmlLineMarkerProvider implements LineMarkerProvider { @Nullable @Override public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement psiElement) { return null; } @Override public void collectSlowLineMarkers(@NotNull List<PsiElement> psiElements, @NotNull Collection<LineMarkerInfo> result) { if(psiElements.size() == 0 || !Symfony2ProjectComponent.isEnabled(psiElements.get(0))) { return; } LazyDecoratedParentServiceValues lazyDecoratedParentServiceValues = null; for (PsiElement psiElement : psiElements) { if(!XmlHelper.getXmlTagNameLeafStartPattern().accepts(psiElement)) { continue; } PsiElement xmlTag = psiElement.getParent(); if(!(xmlTag instanceof XmlTag) || !getServiceIdPattern().accepts(xmlTag)) { continue; } if(lazyDecoratedParentServiceValues == null) { lazyDecoratedParentServiceValues = new LazyDecoratedParentServiceValues(psiElement.getProject()); } // <services><service id="foo"/></services> visitServiceId(psiElement, (XmlTag) xmlTag, result, lazyDecoratedParentServiceValues); } } /** * <service id="foo"/> */ private void visitServiceId(@NotNull PsiElement leafTarget, @NotNull XmlTag xmlTag, @NotNull Collection<LineMarkerInfo> result, @NotNull LazyDecoratedParentServiceValues lazyDecoratedParentServiceValues) { String id = xmlTag.getAttributeValue("id"); if(StringUtils.isBlank(id)) { return; } // <service decorates="foobar" /> String decorates = xmlTag.getAttributeValue("decorates"); if(decorates != null && StringUtils.isNotBlank(decorates)) { result.add(ServiceUtil.getLineMarkerForDecoratesServiceId(leafTarget, ServiceUtil.ServiceLineMarker.DECORATE, decorates)); } // <service parent="foobar" /> String parent = xmlTag.getAttributeValue("parent"); if(parent != null && StringUtils.isNotBlank(parent)) { result.add(ServiceUtil.getLineMarkerForDecoratesServiceId(leafTarget, ServiceUtil.ServiceLineMarker.PARENT, parent)); } // foreign "decorates" linemarker NavigationGutterIconBuilder<PsiElement> lineMarkerDecorates = ServiceUtil.getLineMarkerForDecoratedServiceId( xmlTag.getProject(), ServiceUtil.ServiceLineMarker.DECORATE, lazyDecoratedParentServiceValues.getDecoratedServices(), id ); if(lineMarkerDecorates != null) { result.add(lineMarkerDecorates.createLineMarkerInfo(leafTarget)); } // foreign "parent" linemarker NavigationGutterIconBuilder<PsiElement> lineMarkerParent = ServiceUtil.getLineMarkerForDecoratedServiceId( xmlTag.getProject(), ServiceUtil.ServiceLineMarker.PARENT, lazyDecoratedParentServiceValues.getParentServices(), id ); if(lineMarkerParent != null) { result.add(lineMarkerParent.createLineMarkerInfo(leafTarget)); } } /** * <service id="%foo.class%"/> */ private static XmlTagPattern.Capture getServiceIdPattern() { return XmlPatterns.xmlTag().withName("service") .withChild(XmlPatterns.xmlAttribute().withName("id")).inside( XmlHelper.getInsideTagPattern("services") ).inFile(XmlHelper.getXmlFilePattern()); } }
package com.robust.study.netty.lion.api.spi.net; import java.net.URL; import java.util.Objects; /** * @Description: * @Author: robust * @CreateDate: 2019/8/28 15:49 * @Version: 1.0 */ public class DnsMapping { protected String ip; protected int port; public DnsMapping() { } public DnsMapping(String ip, int port) { this.ip = ip; this.port = port; } public String getIp() { return ip; } public int getPort() { return port; } public DnsMapping setIp(String ip) { this.ip = ip; return this; } public DnsMapping setPort(int port) { this.port = port; return this; } public static DnsMapping parse(String addr) { String[] host_port = Objects.requireNonNull(addr, "dns mapping can not be null").split(":"); if (host_port.length == 1) { return new DnsMapping(host_port[0], 80); } else { return new DnsMapping(host_port[0], Integer.valueOf(host_port[1])); } } public String translate(URL uri) { StringBuilder sb = new StringBuilder(128); sb.append(uri.getProtocol()).append("//") .append(ip) .append(':') .append(port) .append(uri.getPath()); String query = uri.getQuery(); if (query != null) { sb.append('?').append(query); } return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DnsMapping that = (DnsMapping) o; return port == that.port && Objects.equals(ip, that.ip); } @Override public int hashCode() { return Objects.hash(ip, port); } @Override public String toString() { return "DnsMapping{" + "ip='" + ip + '\'' + ", port=" + port + '}'; } }
/* * This file is part of dependency-check-maven. * * 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 (c) 2013 Jeremy Long. All Rights Reserved. */ package org.owasp.dependencycheck.maven; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import java.util.Set; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.data.nvdcve.DatabaseException; import org.owasp.dependencycheck.exception.ExceptionCollection; import org.owasp.dependencycheck.exception.ReportException; import org.owasp.dependencycheck.utils.Settings; /** * Maven Plugin that checks project dependencies and the dependencies of all * child modules to see if they have any known published vulnerabilities. * * @author Jeremy Long */ @Mojo( name = "aggregate", defaultPhase = LifecyclePhase.VERIFY, aggregator = true, threadSafe = false, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresOnline = true ) public class AggregateMojo extends BaseDependencyCheckMojo { /** * Executes the aggregate dependency-check goal. This runs dependency-check * and generates the subsequent reports. * * @throws MojoExecutionException thrown if there is ane exception running * the mojo * @throws MojoFailureException thrown if dependency-check is configured to * fail the build */ @Override public void runCheck() throws MojoExecutionException, MojoFailureException { final Engine engine = loadEngine(); if (engine == null) { return; } ExceptionCollection exCol = scanArtifacts(getProject(), engine); for (MavenProject childProject : getDescendants(this.getProject())) { final ExceptionCollection ex = scanArtifacts(childProject, engine); if (ex != null) { if (exCol == null) { exCol = ex; } exCol.getExceptions().addAll(ex.getExceptions()); if (ex.isFatal()) { exCol.setFatal(true); } } } try { engine.analyzeDependencies(); } catch (ExceptionCollection ex) { if (exCol == null) { exCol = ex; } else if (ex.isFatal()) { exCol.setFatal(true); exCol.getExceptions().addAll(ex.getExceptions()); } if (exCol.isFatal()) { final String msg = String.format("Fatal exception(s) analyzing %s", getProject().getName()); if (this.isFailOnError()) { throw new MojoExecutionException(msg, exCol); } getLog().error(msg); if (getLog().isDebugEnabled()) { getLog().debug(exCol); } return; } else { final String msg = String.format("Exception(s) analyzing %s", getProject().getName()); if (getLog().isDebugEnabled()) { getLog().debug(msg, exCol); } } } File outputDir = getCorrectOutputDirectory(this.getProject()); if (outputDir == null) { //in some regards we shouldn't be writting this, but we are anyway. //we shouldn't write this because nothing is configured to generate this report. outputDir = new File(this.getProject().getBuild().getDirectory()); } try { writeReports(engine, this.getProject(), outputDir); } catch (ReportException ex) { if (exCol == null) { exCol = new ExceptionCollection("Error writing aggregate report", ex); } else { exCol.addException(ex); } if (this.isFailOnError()) { throw new MojoExecutionException("One or more exceptions occurred during dependency-check analysis", exCol); } else { getLog().debug("One or more exceptions occurred during dependency-check analysis", exCol); } } showSummary(this.getProject(), engine.getDependencies()); checkForFailure(engine.getDependencies()); engine.cleanup(); Settings.cleanup(); } /** * Returns a set containing all the descendant projects of the given * project. * * @param project the project for which all descendants will be returned * @return the set of descendant projects */ protected Set<MavenProject> getDescendants(MavenProject project) { if (project == null) { return Collections.emptySet(); } final Set<MavenProject> descendants = new HashSet<MavenProject>(); int size = 0; if (getLog().isDebugEnabled()) { getLog().debug(String.format("Collecting descendants of %s", project.getName())); } for (String m : project.getModules()) { for (MavenProject mod : getReactorProjects()) { try { File mpp = new File(project.getBasedir(), m); mpp = mpp.getCanonicalFile(); if (mpp.compareTo(mod.getBasedir()) == 0 && descendants.add(mod) && getLog().isDebugEnabled()) { getLog().debug(String.format("Decendent module %s added", mod.getName())); } } catch (IOException ex) { if (getLog().isDebugEnabled()) { getLog().debug("Unable to determine module path", ex); } } } } do { size = descendants.size(); for (MavenProject p : getReactorProjects()) { if (project.equals(p.getParent()) || descendants.contains(p.getParent())) { if (descendants.add(p) && getLog().isDebugEnabled()) { getLog().debug(String.format("Decendent %s added", p.getName())); } for (MavenProject modTest : getReactorProjects()) { if (p.getModules() != null && p.getModules().contains(modTest.getName()) && descendants.add(modTest) && getLog().isDebugEnabled()) { getLog().debug(String.format("Decendent %s added", modTest.getName())); } } } final Set<MavenProject> addedDescendants = new HashSet<MavenProject>(); for (MavenProject dec : descendants) { for (String mod : dec.getModules()) { try { File mpp = new File(dec.getBasedir(), mod); mpp = mpp.getCanonicalFile(); if (mpp.compareTo(p.getBasedir()) == 0) { addedDescendants.add(p); } } catch (IOException ex) { if (getLog().isDebugEnabled()) { getLog().debug("Unable to determine module path", ex); } } } } for (MavenProject addedDescendant : addedDescendants) { if (descendants.add(addedDescendant) && getLog().isDebugEnabled()) { getLog().debug(String.format("Decendent module %s added", addedDescendant.getName())); } } } } while (size != 0 && size != descendants.size()); if (getLog().isDebugEnabled()) { getLog().debug(String.format("%s has %d children", project, descendants.size())); } return descendants; } /** * Test if the project has pom packaging * * @param mavenProject Project to test * @return <code>true</code> if it has a pom packaging; otherwise * <code>false</code> */ protected boolean isMultiModule(MavenProject mavenProject) { return "pom".equals(mavenProject.getPackaging()); } /** * Initializes the engine. * * @return the Engine used to execute dependency-check * @throws MojoExecutionException thrown if there is an exception running * the Mojo * @throws MojoFailureException thrown if dependency-check is configured to * fail the build if severe CVEs are identified. */ protected Engine loadEngine() throws MojoExecutionException, MojoFailureException { Engine engine = null; try { engine = initializeEngine(); } catch (DatabaseException ex) { if (getLog().isDebugEnabled()) { getLog().debug("Database connection error", ex); } final String msg = "An exception occurred connecting to the local database. Please see the log file for more details."; if (this.isFailOnError()) { throw new MojoExecutionException(msg, ex); } getLog().error(msg, ex); } return engine; } @Override public boolean canGenerateReport() { return true; //aggregate always returns true for now - we can look at a more complicated/acurate solution later } /** * The name of the report in the site. */ @SuppressWarnings("CanBeFinal") @Parameter(property = "name", defaultValue = "dependency-check:aggregate", required = true) private String name = "dependency-check:aggregate"; /** * Returns the report name. * * @param locale the location * @return the report name */ @Override public String getName(Locale locale) { return name; } /** * Gets the description of the Dependency-Check report to be displayed in * the Maven Generated Reports page. * * @param locale The Locale to get the description for * @return the description */ @Override public String getDescription(Locale locale) { return "Generates an aggregate report of all child Maven projects providing details on any " + "published vulnerabilities within project dependencies. This report is a best " + "effort and may contain false positives and false negatives."; } }
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|cxf operator|. name|transport operator|. name|http package|; end_package begin_import import|import name|java operator|. name|net operator|. name|InetSocketAddress import|; end_import begin_import import|import name|java operator|. name|net operator|. name|Proxy import|; end_import begin_import import|import name|java operator|. name|net operator|. name|URI import|; end_import begin_import import|import name|java operator|. name|util operator|. name|regex operator|. name|Pattern import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|cxf operator|. name|common operator|. name|util operator|. name|StringUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|cxf operator|. name|common operator|. name|util operator|. name|SystemPropertyAction import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|cxf operator|. name|transports operator|. name|http operator|. name|configuration operator|. name|HTTPClientPolicy import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|cxf operator|. name|transports operator|. name|http operator|. name|configuration operator|. name|ProxyServerType import|; end_import begin_class specifier|public class|class name|ProxyFactory block|{ comment|/** * JVM/System property name holding the hostname of the http proxy. */ specifier|private specifier|static specifier|final name|String name|HTTP_PROXY_HOST init|= literal|"http.proxyHost" decl_stmt|; comment|/** * JVM/System property name holding the port of the http proxy. */ specifier|private specifier|static specifier|final name|String name|HTTP_PROXY_PORT init|= literal|"http.proxyPort" decl_stmt|; comment|/** * JVM/System property name holding the list of hosts/patterns that * should not use the proxy configuration. */ specifier|private specifier|static specifier|final name|String name|HTTP_NON_PROXY_HOSTS init|= literal|"http.nonProxyHosts" decl_stmt|; comment|/** * This field holds ONLY the static System proxy configuration: * + http.proxyHost * + http.proxyPort (default 8080) * + http.nonProxyHosts (default null) * It is initialized at the instance creation (and may be null * if there is no appropriate System properties) */ specifier|private name|HTTPClientPolicy name|systemProxyConfiguration decl_stmt|; specifier|public name|ProxyFactory parameter_list|() block|{ name|this operator|. name|systemProxyConfiguration operator|= name|createSystemProxyConfiguration argument_list|() expr_stmt|; block|} specifier|private specifier|static name|HTTPClientPolicy name|createSystemProxyConfiguration parameter_list|() block|{ comment|// Retrieve system properties (if any) name|HTTPClientPolicy name|systemProxyConfiguration init|= literal|null decl_stmt|; name|String name|proxyHost init|= name|SystemPropertyAction operator|. name|getPropertyOrNull argument_list|( name|HTTP_PROXY_HOST argument_list|) decl_stmt|; if|if condition|( name|StringUtils operator|. name|isEmpty argument_list|( name|proxyHost argument_list|) condition|) block|{ name|proxyHost operator|= literal|null expr_stmt|; block|} if|if condition|( name|proxyHost operator|!= literal|null condition|) block|{ comment|// System is configured with a proxy, use it name|systemProxyConfiguration operator|= operator|new name|HTTPClientPolicy argument_list|() expr_stmt|; name|systemProxyConfiguration operator|. name|setProxyServer argument_list|( name|proxyHost argument_list|) expr_stmt|; name|systemProxyConfiguration operator|. name|setProxyServerType argument_list|( name|ProxyServerType operator|. name|HTTP argument_list|) expr_stmt|; comment|// 8080 is the default proxy port value as per some documentation name|String name|proxyPort init|= name|SystemPropertyAction operator|. name|getProperty argument_list|( name|HTTP_PROXY_PORT argument_list|, literal|"8080" argument_list|) decl_stmt|; if|if condition|( name|StringUtils operator|. name|isEmpty argument_list|( name|proxyPort argument_list|) condition|) block|{ name|proxyPort operator|= literal|"8080" expr_stmt|; block|} name|systemProxyConfiguration operator|. name|setProxyServerPort argument_list|( name|Integer operator|. name|parseInt argument_list|( name|proxyPort argument_list|) argument_list|) expr_stmt|; comment|// Load non proxy hosts name|String name|nonProxyHosts init|= name|SystemPropertyAction operator|. name|getPropertyOrNull argument_list|( name|HTTP_NON_PROXY_HOSTS argument_list|) decl_stmt|; if|if condition|( operator|! name|StringUtils operator|. name|isEmpty argument_list|( name|nonProxyHosts argument_list|) condition|) block|{ name|systemProxyConfiguration operator|. name|setNonProxyHosts argument_list|( name|nonProxyHosts argument_list|) expr_stmt|; block|} block|} return|return name|systemProxyConfiguration return|; block|} comment|/** * This method returns the Proxy server should it be set on the * Client Side Policy. * * @return The proxy server or null, if not set. */ specifier|public name|Proxy name|createProxy parameter_list|( name|HTTPClientPolicy name|policy parameter_list|, name|URI name|currentUrl parameter_list|) block|{ if|if condition|( name|policy operator|!= literal|null condition|) block|{ comment|// Maybe the user has provided some proxy information if|if condition|( name|policy operator|. name|isSetProxyServer argument_list|() operator|&& operator|! name|StringUtils operator|. name|isEmpty argument_list|( name|policy operator|. name|getProxyServer argument_list|() argument_list|) condition|) block|{ return|return name|getProxy argument_list|( name|policy argument_list|, name|currentUrl operator|. name|getHost argument_list|() argument_list|) return|; block|} comment|// There is a policy but no Proxy configuration, comment|// fallback on the system proxy configuration return|return name|getSystemProxy argument_list|( name|currentUrl operator|. name|getHost argument_list|() argument_list|) return|; block|} comment|// Use system proxy configuration return|return name|getSystemProxy argument_list|( name|currentUrl operator|. name|getHost argument_list|() argument_list|) return|; block|} comment|/** * Get the system proxy (if any) for the given URL's host. */ specifier|private name|Proxy name|getSystemProxy parameter_list|( name|String name|hostname parameter_list|) block|{ if|if condition|( name|systemProxyConfiguration operator|!= literal|null condition|) block|{ return|return name|getProxy argument_list|( name|systemProxyConfiguration argument_list|, name|hostname argument_list|) return|; block|} comment|// No proxy configured return|return literal|null return|; block|} comment|/** * Honor the nonProxyHosts property value (if set). */ specifier|private name|Proxy name|getProxy parameter_list|( specifier|final name|HTTPClientPolicy name|policy parameter_list|, specifier|final name|String name|hostname parameter_list|) block|{ if|if condition|( name|policy operator|. name|isSetNonProxyHosts argument_list|() condition|) block|{ comment|// Try to match the URL hostname with the exclusion pattern name|Pattern name|pattern init|= name|PatternBuilder operator|. name|build argument_list|( name|policy operator|. name|getNonProxyHosts argument_list|() argument_list|) decl_stmt|; if|if condition|( name|pattern operator|. name|matcher argument_list|( name|hostname argument_list|) operator|. name|matches argument_list|() condition|) block|{ comment|// Excluded hostname -> no proxy return|return name|Proxy operator|. name|NO_PROXY return|; block|} block|} comment|// Either nonProxyHosts is not set or the pattern did not match return|return name|createProxy argument_list|( name|policy argument_list|) return|; block|} comment|/** * Construct a new {@code Proxy} instance from the given policy. */ specifier|private name|Proxy name|createProxy parameter_list|( specifier|final name|HTTPClientPolicy name|policy parameter_list|) block|{ return|return operator|new name|Proxy argument_list|( name|Proxy operator|. name|Type operator|. name|valueOf argument_list|( name|policy operator|. name|getProxyServerType argument_list|() operator|. name|toString argument_list|() argument_list|) argument_list|, operator|new name|InetSocketAddress argument_list|( name|policy operator|. name|getProxyServer argument_list|() argument_list|, name|policy operator|. name|getProxyServerPort argument_list|() argument_list|) argument_list|) return|; block|} block|} end_class end_unit
/** * @作者 Luke * @微信公号 欧诺的小书屋 * @开源项目 $ http://7yue.pro * @免费专栏 $ http://course.7yue.pro * @我的课程 $ http://imooc.com/t/4294850 * @创建时间 2020/3/12 15:51 */ package com.liang.cloudmusic.service.impl; import com.liang.cloudmusic.dto.BlogDTO; import com.liang.cloudmusic.enums.DatabaseOperateType; import com.liang.cloudmusic.model.UnifyResponse; import com.liang.cloudmusic.model.WeiXinConfigParameter; import com.liang.cloudmusic.service.BlogService; import com.liang.cloudmusic.utils.CommonUtil; import com.liang.cloudmusic.utils.DatabaseUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class BlogServiceImpl implements BlogService { @Autowired private DatabaseUtil databaseUtil; @Autowired private WeiXinConfigParameter WXParameter; @Override public UnifyResponse getBlogList(Integer start, Integer count) { // 1. 向数据库查询最新的access_token String access_token = databaseUtil.getAccessToken(); String query = "db.collection('blog').skip(" + start + ").limit(" + count + ").orderBy('createTime', 'desc').get()"; UnifyResponse res = CommonUtil.operatDatabase("", access_token, "cloudmusic-dev-o26dl", DatabaseOperateType.DATABASE_QUERY.getValue(), query); return res; } @Override public UnifyResponse delBlog(BlogDTO blogDTO) { // 向数据库查询最新的access_token String access_token = databaseUtil.getAccessToken(); // 1.删除云数据库中相关内容 String deleteBlog = "db.collection('blog').doc('" + blogDTO.get_id() + "').remove()"; CommonUtil.operatDatabase("", access_token, "cloudmusic-dev-o26dl", DatabaseOperateType.DATABASE_DELETE.getValue(), deleteBlog); // 2.删除blog-comment相关内容 String deleteBlogComment = "db.collection('blog-comment').where({blogId: '" + blogDTO.get_id() + "'}).remove()"; CommonUtil.operatDatabase("", access_token, "cloudmusic-dev-o26dl", DatabaseOperateType.DATABASE_DELETE.getValue(), deleteBlogComment); // 3.删除云存储中的相关照片信息 CommonUtil.delCloundStorage(access_token, "cloudmusic-dev-o26dl", blogDTO.getImg()); UnifyResponse res = new UnifyResponse(20000, "成功"); return res; } }
/* * This code and all components (c) Copyright 2006 - 2018, Wowza Media Systems, LLC. All rights reserved. * This code is licensed pursuant to the Wowza Public License version 1.0, available at www.wowza.com/legal. */ package com.wowza.wms.plugin.avmix; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import com.wowza.util.StringUtils; import com.wowza.wms.application.IApplicationInstance; import com.wowza.wms.logging.WMSLogger; import com.wowza.wms.logging.WMSLoggerFactory; import com.wowza.wms.logging.WMSLoggerIDs; public class AVMixer { private static final String CLASS_NAME = "AVMixer"; private WMSLogger logger; private IApplicationInstance appInstance; private Map<String, OutputStream> outputStreams = new HashMap<String, OutputStream>(); private Map<String, StreamInfo> streamNames = new HashMap<String, StreamInfo>(); private Timer pendingShutdownChecker = null; private Object lock = new Object(); private boolean debugLog = false; public AVMixer(IApplicationInstance appInstance) { this.appInstance = appInstance; logger = WMSLoggerFactory.getLoggerObj(appInstance); debugLog = appInstance.getProperties().getPropertyBoolean("avMixDebugLog", debugLog); if (logger.isDebugEnabled()) debugLog = true; pendingShutdownChecker = new Timer(CLASS_NAME + ".PendingShutdownChecker [" + appInstance.getContextStr() + "]"); pendingShutdownChecker.schedule(new TimerTask() { @Override public void run() { synchronized(lock) { Iterator<String> iter = outputStreams.keySet().iterator(); while (iter.hasNext()) { OutputStream outputStream = outputStreams.get(iter.next()); if (!outputStream.isRunning()) { if (debugLog) logger.info(CLASS_NAME + ".PendingShutdownChecker.run(): " + "[removing output stream " + outputStream.getName() + "]", WMSLoggerIDs.CAT_application, WMSLoggerIDs.EVT_comment); iter.remove(); } } } } }, 1000, 1000); logger.info(CLASS_NAME + ".constructor: [" + appInstance.getContextStr() + "]", WMSLoggerIDs.CAT_application, WMSLoggerIDs.EVT_comment); } public String addOrUpdateOutputStream(String outputName, String videoName, String audioName, long sortDelay, boolean useOriginalTimecodes) { if (StringUtils.isEmpty(outputName)) return "Output Name not set. "; String ret = ""; if (StringUtils.isEmpty(videoName)) videoName = null; if (StringUtils.isEmpty(audioName)) audioName = null; synchronized(lock) { StreamInfo streamInfo = streamNames.get(outputName); if (streamInfo == null) { streamInfo = new StreamInfo(); streamInfo.setOutputName(outputName); streamNames.put(outputName, streamInfo); ret += "Adding Output StreamInfo: " + outputName + ". "; } else { ret += "Updating Output Stream Info: " + outputName + ". "; } streamInfo.setVideoName(videoName); streamInfo.setAudioName(audioName); streamInfo.setSortDelay(sortDelay); streamInfo.setUseOriginalTimeCodes(useOriginalTimecodes); } ret += "Video Source set to " + videoName + ". Audio Source set to " + audioName + ". "; OutputStream outputStream; synchronized(lock) { outputStream = outputStreams.get(outputName); } if (outputStream != null && outputStream.isRunning()) { outputStream.setVideoName(videoName); outputStream.setAudioName(audioName); ret += "Updating Output Stream: " + outputName + ". Video Source set to " + videoName + ". Audio Source set to " + audioName + ". "; } else { ret += startOutputStream(outputName, videoName, audioName, sortDelay, useOriginalTimecodes); } return ret; } public String setVideoSource(String outputName, String videoName) { if (StringUtils.isEmpty(outputName)) return "Output Name not set. "; if (StringUtils.isEmpty(videoName)) videoName = null; String ret = ""; StreamInfo streamInfo; synchronized(lock) { streamInfo = streamNames.get(outputName); if (streamInfo == null) { streamInfo = new StreamInfo(); streamInfo.setOutputName(outputName); streamNames.put(outputName, streamInfo); } streamInfo.setVideoName(videoName); } ret = "Updating Output Stream Info: " + outputName + ". Video Source set to " + videoName + ". "; OutputStream outputStream; synchronized(lock) { outputStream = outputStreams.get(outputName); } if (outputStream != null && outputStream.isRunning()) { outputStream.setVideoName(videoName); } else { ret += startOutputStream(outputName, videoName, streamInfo.getAudioName(), streamInfo.getSortDelay(), streamInfo.isUseOriginalTimeCodes()); } return ret; } public String setAudioSource(String outputName, String audioName) { if (StringUtils.isEmpty(outputName)) return "Output Name not set. "; if (StringUtils.isEmpty(audioName)) audioName = null; String ret = ""; StreamInfo streamInfo; synchronized(lock) { streamInfo = streamNames.get(outputName); if (streamInfo == null) { streamInfo = new StreamInfo(); streamInfo.setOutputName(outputName); streamNames.put(outputName, streamInfo); } streamInfo.setAudioName(audioName); } ret = "Updating Output Stream Info: " + outputName + ". Audio Source set to " + audioName + ". "; OutputStream outputStream; synchronized(lock) { outputStream = outputStreams.get(outputName); } if (outputStream != null && outputStream.isRunning()) { outputStream.setAudioName(audioName); } else { ret += startOutputStream(outputName, streamInfo.getVideoName(), audioName, streamInfo.getSortDelay(), streamInfo.isUseOriginalTimeCodes()); } return ret; } public String removeOutputStream(String outputName) { if (StringUtils.isEmpty(outputName)) return "Output Name not set"; String ret = ""; synchronized(lock) { streamNames.remove(outputName); } ret = "Removed Output Stream Info: " + outputName + ". "; ret += stopOutputStream(outputName, true); return ret; } public void addStream(String streamName) { synchronized(lock) { for (StreamInfo streamInfo : streamNames.values()) { if (streamInfo.getVideoName().equals(streamName) || streamInfo.getAudioName().equals(streamName)) { String ret = ""; ret = startOutputStream(streamInfo.getOutputName(), streamInfo.getVideoName(), streamInfo.getAudioName(), streamInfo.getSortDelay(), streamInfo.isUseOriginalTimeCodes()); logger.info(CLASS_NAME + ".addStream [" + ret + "]"); } } } } public void removeStream(String streamName) { synchronized(lock) { for (StreamInfo streamInfo : streamNames.values()) { if (streamInfo.getVideoName().equals(streamName)) { OutputStream outputStream = outputStreams.get(streamInfo.getOutputName()); if (outputStream != null) { outputStream.setVideoName(null); logger.info(CLASS_NAME + ".removeStream [" + appInstance.getContextStr() + ": Video Source: " + streamName + " removed from " + streamInfo.getOutputName() + "]"); } } if (streamInfo.getAudioName().equals(streamName)) { OutputStream outputStream = outputStreams.get(streamInfo.getOutputName()); if (outputStream != null) { outputStream.setAudioName(null); logger.info(CLASS_NAME + ".removeStream [" + appInstance.getContextStr() + ": Audio Source: " + streamName + " removed from " + streamInfo.getOutputName() + "]"); } } if (streamInfo.getOutputName().equals(streamName)) { outputStreams.remove(streamName); logger.info(CLASS_NAME + ".removeStream [" + appInstance.getContextStr() + ": OutputStream: " + streamName + " unPublished]"); } } } } private String startOutputStream(String outputName, String videoName, String audioName, long sortDelay, boolean useOriginalTimecodes) { String ret = ""; OutputStream outputStream = null; synchronized(lock) { outputStream = outputStreams.get(outputName); } if (outputStream != null && outputStream.isRunning()) { outputStream.setVideoName(videoName); outputStream.setAudioName(audioName); ret = "Output Stream Updated: [" + appInstance.getContextStr() + "/" + outputName + " Video Source: " + videoName + ", Audio Source: " + audioName + "]. "; } else { synchronized(lock) { outputStream = new OutputStream(appInstance, outputName, System.currentTimeMillis(), sortDelay, useOriginalTimecodes); outputStream.setVideoName(videoName); outputStream.setAudioName(audioName); outputStream.setName("AVMixOutputStream: [" + appInstance.getContextStr() + "/" + outputName + "]"); outputStream.setDaemon(true); outputStream.start(); outputStreams.put(outputName, outputStream); ret = "Output Stream Started: [" + appInstance.getContextStr() + "/" + outputName + " Video Source: " + videoName + ", Audio Source: " + audioName + "]. "; } } return ret; } private String stopOutputStream(String outputName, boolean shuttingDown) { if (StringUtils.isEmpty(outputName)) return "Output Name not set. "; String ret = ""; OutputStream outputStream; synchronized(lock) { outputStream = outputStreams.get(outputName); } if (outputStream != null) { if (shuttingDown) { outputStream.close(); } else { outputStream.setVideoName(null); outputStream.setAudioName(null); } ret = "Stopping Output Stream: " + appInstance.getContextStr() + "/" + outputName + ". Delayed: " + !shuttingDown; } else { ret = "Output Stream already stopped: " + appInstance.getContextStr() + "/" + outputName + ". "; } return ret; } public Map<String, OutputStream> getCurrentOutputStreams() { synchronized(lock) { Map<String, OutputStream> streams = new HashMap<String, OutputStream>(); streams.putAll(outputStreams); return streams; } } public Map<String, StreamInfo> getConfiguredOutputStreams() { synchronized(lock) { Map<String, StreamInfo> streams = new HashMap<String, StreamInfo>(); streams.putAll(streamNames); return streams; } } public void close() { List<String> names = new ArrayList<String>(); synchronized(lock) { if (pendingShutdownChecker != null) pendingShutdownChecker.cancel(); pendingShutdownChecker = null; names.addAll(outputStreams.keySet()); } for (String name : names) { stopOutputStream(name, true); } outputStreams.clear(); } @Override public void finalize() { close(); } }
/* * Copyright 2021 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 androidx.car.app.testing; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.mock; import android.app.PendingIntent; import android.content.Intent; import androidx.car.app.AppManager; import androidx.car.app.CarContext; import androidx.car.app.OnRequestPermissionsCallback; import androidx.car.app.ScreenManager; import androidx.car.app.navigation.NavigationManager; import androidx.car.app.testing.navigation.TestNavigationManager; import androidx.test.core.app.ApplicationProvider; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.Shadows; import org.robolectric.annotation.internal.DoNotInstrument; import java.util.ArrayList; import java.util.List; /** Tests for {@link TestCarContext}. */ @RunWith(RobolectricTestRunner.class) @DoNotInstrument public class TestCarContextTest { private final TestCarContext mCarContext = TestCarContext.createCarContext(ApplicationProvider.getApplicationContext()); @Test public void getCarService_appManager_returnsTestAppManager() { assertThat(mCarContext.getCarService(AppManager.class)) .isSameInstanceAs(mCarContext.getCarService(TestAppManager.class)); } @Test public void getCarService_navigationManager_returnsTestNavigationManager() { assertThat(mCarContext.getCarService(NavigationManager.class)) .isSameInstanceAs(mCarContext.getCarService(TestNavigationManager.class)); } @Test public void getCarService_screenManager_returnsTestAppManager() { assertThat(mCarContext.getCarService(ScreenManager.class)) .isSameInstanceAs(mCarContext.getCarService(TestScreenManager.class)); } @Test @SuppressWarnings("PendingIntentMutability") public void getStartCarAppIntents() { Intent startApp = new Intent(Intent.ACTION_VIEW); mCarContext.startCarApp(startApp); assertThat(mCarContext.getStartCarAppIntents()).containsExactly(startApp); Intent broadcast = new Intent("foo"); PendingIntent pendingIntent = PendingIntent.getBroadcast(mCarContext, 1, broadcast, 0); mCarContext.getFakeHost().performNotificationActionClick(pendingIntent); Intent broadcastedIntent = Shadows.shadowOf(mCarContext).getBroadcastIntents().get(0); Intent startApp2 = new Intent(Intent.ACTION_SEND); CarContext.startCarApp(broadcastedIntent, startApp2); assertThat(mCarContext.getStartCarAppIntents()).containsExactly(startApp, startApp2); } @Test public void hasCalledFinishCarApp() { assertThat(mCarContext.hasCalledFinishCarApp()).isFalse(); mCarContext.finishCarApp(); assertThat(mCarContext.hasCalledFinishCarApp()).isTrue(); } @Test public void getLastPermissionRequest() { assertThat(mCarContext.getLastPermissionRequest()).isNull(); List<String> permissions = new ArrayList<>(); permissions.add("foo"); OnRequestPermissionsCallback callback = mock(OnRequestPermissionsCallback.class); mCarContext.requestPermissions(permissions, callback); TestCarContext.PermissionRequest request = mCarContext.getLastPermissionRequest(); assertThat(request.getPermissionsRequested()).containsExactlyElementsIn(permissions); assertThat(request.getCallback()).isEqualTo(callback); } }
// Copyright 2011-2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Views.Help; import java.net.URL; import com.google.security.zynamics.binnavi.Help.CHelpFunctions; import com.google.security.zynamics.binnavi.Help.IHelpInformation; /** * Context-sensitive help information for fields used to filter view tables. */ public final class CViewFilterHelp implements IHelpInformation { @Override public String getText() { return "You can use this input field to filter the visible views.\n\nFilter by view name: Enter the view name\nFilter by view description: Enter the view description\nFilter by node count: nodes ==/!=/</>/<=/>= value\nFilter by edge count: edges ==/!=/</>/<=/>= value\nFilter by containing instruction: contains == HexAddress"; } @Override public URL getUrl() { return CHelpFunctions.urlify(CHelpFunctions.MAIN_WINDOW_FILE); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.search.documents.implementation.converters; import com.azure.search.documents.indexes.models.KeepTokenFilter; import java.util.ArrayList; import java.util.List; /** * A converter between {@link com.azure.search.documents.indexes.implementation.models.KeepTokenFilter} and * {@link KeepTokenFilter}. */ public final class KeepTokenFilterConverter { /** * Maps from {@link com.azure.search.documents.indexes.implementation.models.KeepTokenFilter} to {@link KeepTokenFilter}. */ public static KeepTokenFilter map(com.azure.search.documents.indexes.implementation.models.KeepTokenFilter obj) { if (obj == null) { return null; } KeepTokenFilter keepTokenFilter = new KeepTokenFilter(); String name = obj.getName(); keepTokenFilter.setName(name); if (obj.getKeepWords() != null) { List<String> keepWords = new ArrayList<>(obj.getKeepWords()); keepTokenFilter.setKeepWords(keepWords); } Boolean lowerCaseKeepWords = obj.isLowerCaseKeepWords(); keepTokenFilter.setLowerCaseKeepWords(lowerCaseKeepWords); return keepTokenFilter; } /** * Maps from {@link KeepTokenFilter} to {@link com.azure.search.documents.indexes.implementation.models.KeepTokenFilter}. */ public static com.azure.search.documents.indexes.implementation.models.KeepTokenFilter map(KeepTokenFilter obj) { if (obj == null) { return null; } com.azure.search.documents.indexes.implementation.models.KeepTokenFilter keepTokenFilter = new com.azure.search.documents.indexes.implementation.models.KeepTokenFilter(); String name = obj.getName(); keepTokenFilter.setName(name); if (obj.getKeepWords() != null) { List<String> keepWords = new ArrayList<>(obj.getKeepWords()); keepTokenFilter.setKeepWords(keepWords); } Boolean lowerCaseKeepWords = obj.isLowerCaseKeepWords(); keepTokenFilter.setLowerCaseKeepWords(lowerCaseKeepWords); return keepTokenFilter; } private KeepTokenFilterConverter() { } }
/* * Licensed to the University of California, Berkeley 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 tachyon.underfs.glusterfs; import org.apache.hadoop.conf.Configuration; import tachyon.Constants; import tachyon.conf.TachyonConf; import tachyon.underfs.hdfs.HdfsUnderFileSystem; /** * A variant of {@link HdfsUnderFileSystem} that instead uses the Gluster FS * <p> * Currently this implementation simply manages the extra configuration setup necessary to connect * to Gluster FS * </p> * */ public class GlusterFSUnderFileSystem extends HdfsUnderFileSystem { /** * Constant for the Gluster FS URI scheme */ public static final String SCHEME = "glusterfs://"; public GlusterFSUnderFileSystem(String fsDefaultName, TachyonConf tachyonConf, Object conf) { super(fsDefaultName, tachyonConf, conf); } @Override public UnderFSType getUnderFSType() { return UnderFSType.GLUSTERFS; } @Override protected void prepareConfiguration(String path, TachyonConf tachyonConf, Configuration config) { if (path.startsWith(SCHEME)) { // Configure for Gluster FS config.set("fs.glusterfs.impl", tachyonConf.get(Constants.UNDERFS_GLUSTERFS_IMPL)); config.set("mapred.system.dir", tachyonConf.get(Constants.UNDERFS_GLUSTERFS_MR_DIR)); config .set("fs.glusterfs.volumes", tachyonConf.get(Constants.UNDERFS_GLUSTERFS_VOLUMES)); config.set( "fs.glusterfs.volume.fuse." + tachyonConf.get(Constants.UNDERFS_GLUSTERFS_VOLUMES), tachyonConf.get(Constants.UNDERFS_GLUSTERFS_MOUNTS)); } else { // If not Gluster FS fall back to default HDFS behaviour // This should only happen if someone creates an instance of this directly rather than via the // registry and factory which enforces the GlusterFS prefix being present. super.prepareConfiguration(path, tachyonConf, config); } } }
package com.aitlp.system.controller; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.aitlp.system.service.ISysLogininforService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.aitlp.common.core.constant.Constants; import com.aitlp.common.core.utils.ServletUtils; import com.aitlp.common.core.utils.ip.IpUtils; import com.aitlp.common.core.utils.poi.ExcelUtil; import com.aitlp.common.core.web.controller.BaseController; import com.aitlp.common.core.web.domain.AjaxResult; import com.aitlp.common.core.web.page.TableDataInfo; import com.aitlp.common.log.annotation.Log; import com.aitlp.common.log.enums.BusinessType; import com.aitlp.common.security.annotation.PreAuthorize; import com.aitlp.system.domain.SysLogininfor; /** * 系统访问记录 * * @author Winbert */ @RestController @RequestMapping("/logininfor") public class SysLogininforController extends BaseController { @Autowired private ISysLogininforService logininforService; @PreAuthorize(hasPermi = "system:logininfor:list") @GetMapping("/list") public TableDataInfo list(SysLogininfor logininfor) { startPage(); List<SysLogininfor> list = logininforService.selectLogininforList(logininfor); return getDataTable(list); } @Log(title = "登录日志", businessType = BusinessType.EXPORT) @PreAuthorize(hasPermi = "system:logininfor:export") @PostMapping("/export") public void export(HttpServletResponse response, SysLogininfor logininfor) throws IOException { List<SysLogininfor> list = logininforService.selectLogininforList(logininfor); ExcelUtil<SysLogininfor> util = new ExcelUtil<SysLogininfor>(SysLogininfor.class); util.exportExcel(response, list, "登录日志"); } @PreAuthorize(hasPermi = "system:logininfor:remove") @Log(title = "登录日志", businessType = BusinessType.DELETE) @DeleteMapping("/{infoIds}") public AjaxResult remove(@PathVariable Long[] infoIds) { return toAjax(logininforService.deleteLogininforByIds(infoIds)); } @PreAuthorize(hasPermi = "system:logininfor:remove") @Log(title = "登录日志", businessType = BusinessType.DELETE) @DeleteMapping("/clean") public AjaxResult clean() { logininforService.cleanLogininfor(); return AjaxResult.success(); } @PostMapping public AjaxResult add(@RequestParam("username") String username, @RequestParam("status") String status, @RequestParam("message") String message) { String ip = IpUtils.getIpAddr(ServletUtils.getRequest()); // 封装对象 SysLogininfor logininfor = new SysLogininfor(); logininfor.setUserName(username); logininfor.setIpaddr(ip); logininfor.setMsg(message); // 日志状态 if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) { logininfor.setStatus("0"); } else if (Constants.LOGIN_FAIL.equals(status)) { logininfor.setStatus("1"); } return toAjax(logininforService.insertLogininfor(logininfor)); } }
/* * Copyright 2018 Netflix, 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.netflix.titus.testkit.client; import java.util.HashMap; import java.util.Map; import com.netflix.titus.api.model.callmetadata.CallMetadata; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.event.JobManagerEvent; import com.netflix.titus.api.jobmanager.model.job.event.JobUpdateEvent; import com.netflix.titus.api.jobmanager.model.job.event.TaskUpdateEvent; import com.netflix.titus.common.util.rx.ObservableExt; import com.netflix.titus.common.util.tuple.Pair; import com.netflix.titus.grpc.protogen.JobChangeNotification; import com.netflix.titus.runtime.endpoint.v3.grpc.GrpcJobManagementModelConverters; import rx.Observable; public class V3ClientUtils { private static final CallMetadata callMetadata = CallMetadata.newBuilder().withCallerId("StubbedJobData").build(); public static Observable<JobManagerEvent<?>> observeJobs(Observable<JobChangeNotification> grpcEvents) { return grpcEvents.filter(V3ClientUtils::isJobOrTaskUpdate) .compose(ObservableExt.mapWithState(new HashMap<>(), V3ClientUtils::toCoreEvent)); } private static Pair<JobManagerEvent<?>, Map<String, Object>> toCoreEvent(JobChangeNotification event, Map<String, Object> state) { if (event.getNotificationCase() == JobChangeNotification.NotificationCase.JOBUPDATE) { Job<?> job = GrpcJobManagementModelConverters.toCoreJob(event.getJobUpdate().getJob()); Object previous = state.get(job.getId()); state.put(job.getId(), job); if (previous == null) { return Pair.of(JobUpdateEvent.newJob(job, callMetadata), state); } return Pair.of(JobUpdateEvent.jobChange(job, (Job<?>) previous, callMetadata), state); } // Task update com.netflix.titus.grpc.protogen.Task grpcTask = event.getTaskUpdate().getTask(); Job<?> job = (Job<?>) state.get(grpcTask.getJobId()); Task task = GrpcJobManagementModelConverters.toCoreTask(job, grpcTask); Object previous = state.get(task.getId()); state.put(task.getId(), task); if (event.getTaskUpdate().getMovedFromAnotherJob()) { return Pair.of(TaskUpdateEvent.newTaskFromAnotherJob(job, task, callMetadata), state); } else if (previous == null) { return Pair.of(TaskUpdateEvent.newTask(job, task, callMetadata), state); } return Pair.of(TaskUpdateEvent.taskChange(job, task, (Task) previous, callMetadata), state); } private static boolean isJobOrTaskUpdate(JobChangeNotification event) { return event.getNotificationCase() == JobChangeNotification.NotificationCase.JOBUPDATE || event.getNotificationCase() == JobChangeNotification.NotificationCase.TASKUPDATE; } }
package com.liyafeng.view.webview; import android.util.Log; import android.webkit.JavascriptInterface; public class JsObject { @JavascriptInterface public void execute(String msg) { Log.i("test", "调用了execute" + msg); } }
package com.atguigu.gmall.sms.dao; import com.atguigu.gmall.sms.entity.CategoryBoundsEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 商品分类积分设置 * * @author Qiao * @email lxf@atguigu.com * @date 2020-04-28 11:45:59 */ @Mapper public interface CategoryBoundsDao extends BaseMapper<CategoryBoundsEntity> { }
/* * Copyright (C) 2011 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 android.view; public abstract class ActionProvider { public static interface VisibilityListener { public abstract void onActionProviderVisibilityChanged(boolean isVisible); } public ActionProvider(android.content.Context context) { throw new RuntimeException("Stub!"); } @java.lang.Deprecated() public abstract android.view.View onCreateActionView(); public android.view.View onCreateActionView(android.view.MenuItem forItem) { throw new RuntimeException("Stub!"); } public boolean overridesItemVisibility() { throw new RuntimeException("Stub!"); } public boolean isVisible() { throw new RuntimeException("Stub!"); } public void refreshVisibility() { throw new RuntimeException("Stub!"); } public boolean onPerformDefaultAction() { throw new RuntimeException("Stub!"); } public boolean hasSubMenu() { throw new RuntimeException("Stub!"); } public void onPrepareSubMenu(android.view.SubMenu subMenu) { throw new RuntimeException("Stub!"); } public void setVisibilityListener(android.view.ActionProvider.VisibilityListener listener) { throw new RuntimeException("Stub!"); } }
package io.meeting.entity; /** * 列的属性 * * @author neckhyg * @email 497273569@qq.com * @date 2016年12月20日 上午12:01:45 */ public class ColumnEntity { //列名 private String columnName; //列名类型 private String dataType; //列名备注 private String comments; //属性名称(第一个字母大写),如:user_name => UserName private String attrName; //属性名称(第一个字母小写),如:user_name => userName private String attrname; //属性类型 private String attrType; //auto_increment private String extra; public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public String getAttrname() { return attrname; } public void setAttrname(String attrname) { this.attrname = attrname; } public String getAttrName() { return attrName; } public void setAttrName(String attrName) { this.attrName = attrName; } public String getAttrType() { return attrType; } public void setAttrType(String attrType) { this.attrType = attrType; } public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } }
package net.studymongolian.mongollibrary; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import java.util.ArrayList; import java.util.List; public class KeyboardAeiou extends Keyboard { // name to use in the keyboard popup chooser private static final String DEFAULT_DISPLAY_NAME = "ᠴᠠᠭᠠᠨ ᠲᠣᠯᠤᠭᠠᠢ"; // Row 1 protected KeyText mKeyA; protected KeyText mKeyE; protected KeyText mKeyI; protected KeyText mKeyO; protected KeyText mKeyU; // Row 2 protected KeyText mKeyNA; protected KeyText mKeyBA; protected KeyText mKeyQA; protected KeyText mKeyGA; protected KeyText mKeyMA; protected KeyText mKeyLA; // Row 3 protected KeyText mKeySA; protected KeyText mKeyTADA; protected KeyText mKeyCHA; protected KeyText mKeyJA; protected KeyText mKeyYA; protected KeyText mKeyRA; // Row 4 protected KeyKeyboardChooser mKeyKeyboard; protected KeyText mKeyComma; protected KeyText mKeySpace; protected KeyBackspace mKeyBackspace; protected KeyImage mKeyReturn; private static final String NEWLINE = "\n"; private static final String KEY_SPACE_SUB_DISPLAY = "ᠶ᠋ᠢ ᠳᠤ ᠤᠨ"; public KeyboardAeiou(Context context) { super(context); init(context); } public KeyboardAeiou(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public KeyboardAeiou(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } protected void init(Context context) { // | A | E | I | O | U | Row 1 // | N | B | Q | G | M | L | Row 2 // | S | D | Ch| J | Y | R | Row 3 // |kb | , | space |ret|del| Row 4 // actual layout work is done by Keyboard superclass's onLayout mNumberOfKeysInRow = new int[]{5, 6, 6, 5}; // the key weights for each row should sum to 1 mKeyWeights = new float[]{ 1 / 5f, 1 / 5f, 1 / 5f, 1 / 5f, 1 / 5f, // row 0 1 / 6f, 1 / 6f, 1 / 6f, 1 / 6f, 1 / 6f, 1 / 6f, // row 1 1 / 6f, 1 / 6f, 1 / 6f, 1 / 6f, 1 / 6f, 1 / 6f, // row 2 1 / 6f, 1 / 6f, 2 / 6f, 1 / 6f, 1 / 6f}; // row 3 instantiateKeys(context); setKeyValues(); setNonChangingKeyValues(); setKeyImages(); setListeners(); addKeysToKeyboard(); applyThemeToKeys(); } private void instantiateKeys(Context context) { // Row 1 mKeyA = new KeyText(context); mKeyE = new KeyText(context); mKeyI = new KeyText(context); mKeyO = new KeyText(context); mKeyU = new KeyText(context); // Row 2 mKeyNA = new KeyText(context); mKeyBA = new KeyText(context); mKeyQA = new KeyText(context); mKeyGA = new KeyText(context); mKeyMA = new KeyText(context); mKeyLA = new KeyText(context); // Row 3 mKeySA = new KeyText(context); mKeyTADA = new KeyText(context); mKeyCHA = new KeyText(context); mKeyJA = new KeyText(context); mKeyYA = new KeyText(context); mKeyRA = new KeyText(context); // Row 4 mKeyKeyboard = new KeyKeyboardChooser(context); mKeyComma = new KeyText(context); mKeySpace = new KeyText(context); mKeyReturn = new KeyImage(context); mKeyBackspace = new KeyBackspace(context); } private void setKeyValues() { rotatePrimaryTextForSelectKeys(); rotateSecondaryTextForSelectedKeys(); // Row 1 mKeyA.setText(MongolCode.Uni.A); mKeyA.setSwipeUpText(null); mKeyA.setSubText("" + MongolCode.Uni.ZWJ + MongolCode.Uni.A + MongolCode.Uni.FVS1); mKeyE.setText(MongolCode.Uni.E); mKeyE.setSwipeUpText(MongolCode.Uni.EE); mKeyE.setSubText(MongolCode.Uni.EE); mKeyI.setText(MongolCode.Uni.I); mKeyI.setSwipeUpText(null); mKeyI.setSubText(""); mKeyO.setText(MongolCode.Uni.U); mKeyO.setSwipeUpText(null); mKeyO.setSubText(""); mKeyU.setText(MongolCode.Uni.UE); mKeyU.setSwipeUpText(null); mKeyU.setSubText(""); // Row 2 mKeyNA.setText(MongolCode.Uni.NA); mKeyNA.setSwipeUpText(MongolCode.Uni.ANG); mKeyNA.setSubText(MongolCode.Uni.ANG); mKeyBA.setText(MongolCode.Uni.BA); mKeyBA.setSwipeUpText(MongolCode.Uni.PA); mKeyBA.setSubText(MongolCode.Uni.PA); mKeyQA.setText(MongolCode.Uni.QA); mKeyQA.setSwipeUpText(MongolCode.Uni.HAA); mKeyQA.setSubText(MongolCode.Uni.HAA); mKeyGA.setText(MongolCode.Uni.GA); mKeyGA.setSwipeUpText(MongolCode.Uni.KA); mKeyGA.setSubText(MongolCode.Uni.KA); mKeyMA.setText(MongolCode.Uni.MA); mKeyMA.setSwipeUpText(null); mKeyMA.setSubText(""); mKeyLA.setText(MongolCode.Uni.LA); mKeyLA.setSwipeUpText(MongolCode.Uni.LHA); mKeyLA.setSubText(MongolCode.Uni.LHA); // Row 3 mKeySA.setText(MongolCode.Uni.SA); mKeySA.setSwipeUpText(MongolCode.Uni.SHA); mKeySA.setSubText(MongolCode.Uni.SHA); mKeyTADA.setText(MongolCode.Uni.DA, MongolCode.Uni.TA); mKeyTADA.setSwipeUpText(null); mKeyTADA.setSubText(MongolCode.Uni.DA); mKeyCHA.setText(MongolCode.Uni.CHA); mKeyCHA.setSwipeUpText(MongolCode.Uni.ZA); mKeyCHA.setSubText(MongolCode.Uni.ZA); mKeyJA.setText(MongolCode.Uni.JA); mKeyJA.setSwipeUpText(MongolCode.Uni.ZHI); mKeyJA.setSubText(MongolCode.Uni.ZHI); mKeyYA.setText(MongolCode.Uni.YA); mKeyYA.setSwipeUpText(MongolCode.Uni.WA); mKeyYA.setSubText(MongolCode.Uni.WA); mKeyRA.setText(MongolCode.Uni.RA); mKeyRA.setSwipeUpText(MongolCode.Uni.ZRA); mKeyRA.setSubText(MongolCode.Uni.ZRA); // Row 4 mKeyComma.setText(MongolCode.Uni.MONGOLIAN_COMMA); mKeyComma.setSwipeUpText(MongolCode.Uni.VERTICAL_QUESTION_MARK); mKeyComma.setSubText(MongolCode.Uni.VERTICAL_QUESTION_MARK); } private void rotatePrimaryTextForSelectKeys() { mKeyNA.setIsRotatedPrimaryText(true); mKeyBA.setIsRotatedPrimaryText(true); mKeyQA.setIsRotatedPrimaryText(true); mKeyGA.setIsRotatedPrimaryText(true); mKeyMA.setIsRotatedPrimaryText(true); mKeySA.setIsRotatedPrimaryText(true); mKeyTADA.setIsRotatedPrimaryText(true); mKeyCHA.setIsRotatedPrimaryText(true); mKeyJA.setIsRotatedPrimaryText(true); mKeyYA.setIsRotatedPrimaryText(true); mKeyComma.setIsRotatedPrimaryText(true); } private void dontRotatePrimaryTextForSelectKeys() { mKeyNA.setIsRotatedPrimaryText(false); mKeyBA.setIsRotatedPrimaryText(false); mKeyQA.setIsRotatedPrimaryText(false); mKeyGA.setIsRotatedPrimaryText(false); mKeyMA.setIsRotatedPrimaryText(false); mKeySA.setIsRotatedPrimaryText(false); mKeyTADA.setIsRotatedPrimaryText(false); mKeyCHA.setIsRotatedPrimaryText(false); mKeyJA.setIsRotatedPrimaryText(false); mKeyYA.setIsRotatedPrimaryText(false); mKeyComma.setIsRotatedPrimaryText(false); } private void rotateSecondaryTextForSelectedKeys() { mKeyComma.setIsRotatedSubText(true); } private void dontRotateSecondaryTextForSelectedKeys() { mKeyComma.setIsRotatedSubText(false); } private void setPunctuationKeyValues() { dontRotatePrimaryTextForSelectKeys(); dontRotateSecondaryTextForSelectedKeys(); // Row 1 mKeyA.setText(MongolCode.Uni.VERTICAL_LEFT_PARENTHESIS); mKeyA.setSwipeUpText(MongolCode.Uni.VERTICAL_LEFT_SQUARE_BRACKET); mKeyA.setSubText(MongolCode.Uni.VERTICAL_LEFT_SQUARE_BRACKET); mKeyE.setText(MongolCode.Uni.VERTICAL_RIGHT_PARENTHESIS); mKeyE.setSwipeUpText(MongolCode.Uni.VERTICAL_RIGHT_SQUARE_BRACKET); mKeyE.setSubText(MongolCode.Uni.VERTICAL_RIGHT_SQUARE_BRACKET); mKeyI.setText(MongolCode.Uni.VERTICAL_LEFT_DOUBLE_ANGLE_BRACKET); mKeyI.setSwipeUpText(MongolCode.Uni.VERTICAL_LEFT_ANGLE_BRACKET); mKeyI.setSubText(MongolCode.Uni.VERTICAL_LEFT_ANGLE_BRACKET); mKeyO.setText(MongolCode.Uni.VERTICAL_RIGHT_DOUBLE_ANGLE_BRACKET); mKeyO.setSwipeUpText(MongolCode.Uni.VERTICAL_RIGHT_ANGLE_BRACKET); mKeyO.setSubText(MongolCode.Uni.VERTICAL_RIGHT_ANGLE_BRACKET); mKeyU.setText(MongolCode.Uni.MIDDLE_DOT); mKeyU.setSwipeUpText(MongolCode.Uni.MONGOLIAN_ELLIPSIS); mKeyU.setSubText(MongolCode.Uni.MONGOLIAN_ELLIPSIS); // Row 2 mKeyNA.setText("1"); mKeyNA.setSwipeUpText("①"); mKeyNA.setSubText("①"); mKeyBA.setText("2"); mKeyBA.setSwipeUpText("②"); mKeyBA.setSubText("②"); mKeyQA.setText("3"); mKeyQA.setSwipeUpText("③"); mKeyQA.setSubText("③"); mKeyGA.setText("4"); mKeyGA.setSwipeUpText("④"); mKeyGA.setSubText("④"); mKeyMA.setText("5"); mKeyMA.setSwipeUpText("⑤"); mKeyMA.setSubText("⑤"); mKeyLA.setText(MongolCode.Uni.VERTICAL_EM_DASH); mKeyLA.setSwipeUpText("~"); mKeyLA.setSubText("~"); // Row 3 mKeySA.setText("6"); mKeySA.setSwipeUpText("⑥"); mKeySA.setSubText("⑥"); mKeyTADA.setText("7"); mKeyTADA.setSwipeUpText("⑦"); mKeyTADA.setSubText("⑦"); mKeyCHA.setText("8"); mKeyCHA.setSwipeUpText("⑧"); mKeyCHA.setSubText("⑧"); mKeyJA.setText("9"); mKeyJA.setSwipeUpText("⑨"); mKeyJA.setSubText("⑨"); mKeyYA.setText("0"); mKeyYA.setSwipeUpText("⑩"); mKeyYA.setSubText("⑩"); mKeyRA.setText(MongolCode.Uni.QUESTION_EXCLAMATION_MARK); mKeyRA.setSwipeUpText(MongolCode.Uni.DOUBLE_QUESTION_MARK); mKeyRA.setSubText(MongolCode.Uni.DOUBLE_QUESTION_MARK); // Row 4 mKeyComma.setText("."); mKeyComma.setSwipeUpText("-"); mKeyComma.setSubText("-"); } private void setNonChangingKeyValues() { mKeySpace.setText(" "); mKeySpace.setSwipeUpText(MongolCode.Uni.NNBS); if (hasCandidatesView()) { mKeySpace.setSubText(KEY_SPACE_SUB_DISPLAY); } mKeyReturn.setText(NEWLINE); } private void setKeyImages() { mKeyBackspace.setImage(getBackspaceImage(), getPrimaryTextColor()); mKeyKeyboard.setImage(getKeyboardImage(), getPrimaryTextColor()); mKeyReturn.setImage(getReturnImage(), getPrimaryTextColor()); } private void setListeners() { // Row 1 mKeyA.setKeyListener(this); mKeyE.setKeyListener(this); mKeyI.setKeyListener(this); mKeyO.setKeyListener(this); mKeyU.setKeyListener(this); // Row 2 mKeyNA.setKeyListener(this); mKeyBA.setKeyListener(this); mKeyQA.setKeyListener(this); mKeyGA.setKeyListener(this); mKeyMA.setKeyListener(this); mKeyLA.setKeyListener(this); // Row 3 mKeySA.setKeyListener(this); mKeyTADA.setKeyListener(this); mKeyCHA.setKeyListener(this); mKeyJA.setKeyListener(this); mKeyYA.setKeyListener(this); mKeyRA.setKeyListener(this); // Row 4 mKeyKeyboard.setKeyListener(this); mKeyComma.setKeyListener(this); mKeySpace.setKeyListener(this); mKeyReturn.setKeyListener(this); mKeyBackspace.setKeyListener(this); } private void addKeysToKeyboard() { // Row 1 addView(mKeyA); addView(mKeyE); addView(mKeyI); addView(mKeyO); addView(mKeyU); // Row 2 addView(mKeyNA); addView(mKeyBA); addView(mKeyQA); addView(mKeyGA); addView(mKeyMA); addView(mKeyLA); // Row 3 addView(mKeySA); addView(mKeyTADA); addView(mKeyCHA); addView(mKeyJA); addView(mKeyYA); addView(mKeyRA); // Row 4 addView(mKeyKeyboard); addView(mKeyComma); addView(mKeySpace); addView(mKeyReturn); addView(mKeyBackspace); } public List<PopupKeyCandidate> getPopupCandidates(Key key) { // get the appropriate candidates based on the key pressed if (key == mKeyA) { return getCandidatesForA(); } else if (key == mKeyE) { return getCandidatesForE(); } else if (key == mKeyI) { return getCandidatesForI(); } else if (key == mKeyO) { return getCandidatesForO(); } else if (key == mKeyU) { return getCandidatesForU(); } else if (key == mKeyNA) { return getCandidatesForNA(); } else if (key == mKeyBA) { return getCandidatesForBA(); } else if (key == mKeyQA) { return getCandidatesForQA(); } else if (key == mKeyGA) { return getCandidatesForGA(); } else if (key == mKeyMA) { return getCandidatesForMA(); } else if (key == mKeyLA) { return getCandidatesForLA(); } else if (key == mKeySA) { return getCandidatesForSA(); } else if (key == mKeyTADA) { return getCandidatesForTADA(); } else if (key == mKeyCHA) { return getCandidatesForCHA(); } else if (key == mKeyJA) { return getCandidatesForJA(); } else if (key == mKeyYA) { return getCandidatesForYA(); } else if (key == mKeyRA) { return getCandidatesForRA(); } else if (key == mKeyKeyboard) { return getCandidatesForKeyboardKey(); } else if (key == mKeyComma) { return getCandidatesForComma(); } else if (key == mKeySpace) { return getCandidatesForSpace(); } return null; } private List<PopupKeyCandidate> getCandidatesForA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate(MongolCode.Uni.VERTICAL_LEFT_SQUARE_BRACKET)); return candidates; } PopupKeyCandidate nirugu = new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_NIRUGU); PopupKeyCandidate zwj = new PopupKeyCandidate( "" + MongolCode.Uni.ZWJ, "" + "|"); if (isIsolateOrInitial()) { candidates.add(new PopupKeyCandidate("" + MongolCode.Uni.A + MongolCode.Uni.FVS1)); candidates.add(nirugu); candidates.add(zwj); return candidates; } // MVS-A char previousChar = getPreviousChar(); if (MongolCode.isMvsPrecedingChar(previousChar)) { PopupKeyCandidate mvs_a = new PopupKeyCandidate( "" + MongolCode.Uni.MVS + MongolCode.Uni.A, "" + MongolCode.Uni.ZWJ + previousChar + MongolCode.Uni.MVS + MongolCode.Uni.A, null); candidates.add(mvs_a); } PopupKeyCandidate medial_A_FVS1 = new PopupKeyCandidate( "" + MongolCode.Uni.A + MongolCode.Uni.FVS1, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.A + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ, "" + MongolCode.Uni.A + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ); candidates.add(medial_A_FVS1); PopupKeyCandidate final_A_FVS1 = new PopupKeyCandidate( "" + MongolCode.Uni.A + MongolCode.Uni.FVS1, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.A + MongolCode.Uni.FVS1, null); candidates.add(final_A_FVS1); candidates.add(nirugu); candidates.add(zwj); return candidates; } private List<PopupKeyCandidate> getCandidatesForE() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate(MongolCode.Uni.VERTICAL_RIGHT_SQUARE_BRACKET)); return candidates; } if (!isIsolateOrInitial()) { // MVS char previousChar = getPreviousChar(); if (MongolCode.isMvsPrecedingChar(previousChar) && previousChar != MongolCode.Uni.QA && previousChar != MongolCode.Uni.GA) { PopupKeyCandidate mvs_E = new PopupKeyCandidate( "" + MongolCode.Uni.MVS + MongolCode.Uni.E, "" + MongolCode.Uni.ZWJ + previousChar + MongolCode.Uni.MVS + MongolCode.Uni.E); candidates.add(mvs_E); } } candidates.add(new PopupKeyCandidate(MongolCode.Uni.EE)); if (!isIsolateOrInitial()) { PopupKeyCandidate final_E_FVS1 = new PopupKeyCandidate( "" + MongolCode.Uni.E + MongolCode.Uni.FVS1, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.E + MongolCode.Uni.FVS1, null); candidates.add(final_E_FVS1); } if (shouldShowSuffixesInPopup()) { candidates.addAll(getSuffixForKeyE()); } return candidates; } private List<PopupKeyCandidate> getSuffixForKeyE() { List<PopupKeyCandidate> suffixes = new ArrayList<>(); if (mKeyboardListener == null) return suffixes; String previousWord = mKeyboardListener.getPreviousMongolWord(true); MongolCode.Gender gender = MongolCode.getWordGender(previousWord); String achaEche = MongolCode.getSuffixAchaEche(gender); suffixes.add(new PopupKeyCandidate(achaEche)); return suffixes; } private List<PopupKeyCandidate> getCandidatesForI() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate(MongolCode.Uni.VERTICAL_LEFT_ANGLE_BRACKET)); return candidates; } if (!isIsolateOrInitial()) { PopupKeyCandidate medial_I_FVS1 = new PopupKeyCandidate( "" + MongolCode.Uni.I + MongolCode.Uni.FVS1, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.I + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ, "" + MongolCode.Uni.I + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ); candidates.add(medial_I_FVS1); char prevChar = getPreviousChar(); if (MongolCode.isVowel(prevChar)) { // override double tooth I after vowel (Unicode 10.0 deviation) // ("" + MongolCode.Uni.ZWJ + MongolCode.Uni.I) is an alternate method to override double tooth I PopupKeyCandidate medial_I_FVS2 = new PopupKeyCandidate( "" + MongolCode.Uni.I + MongolCode.Uni.FVS2, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.I + MongolCode.Uni.ZWJ, "" + MongolCode.Uni.I + MongolCode.Uni.FVS2 + MongolCode.Uni.ZWJ); candidates.add(medial_I_FVS2); } } if (shouldShowSuffixesInPopup()) { candidates.addAll(getSuffixForKeyI()); } return candidates; } private List<PopupKeyCandidate> getSuffixForKeyI() { List<PopupKeyCandidate> suffixes = new ArrayList<>(); if (mKeyboardListener == null) return suffixes; String previousWord = mKeyboardListener.getPreviousMongolWord(true); if (TextUtils.isEmpty(previousWord)) { suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.I)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.YI)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.YIN)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.IYAR)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.IYAN)); return suffixes; } // YI I char lastChar = previousWord.charAt(previousWord.length() - 1); String iYi = MongolCode.getSuffixYiI(lastChar); suffixes.add(new PopupKeyCandidate(iYi)); // YIN suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.YIN)); // IYAR and IYAN MongolCode.Gender gender = MongolCode.getWordGender(previousWord); if (gender == MongolCode.Gender.FEMININE) { suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.IYER)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.IYEN)); } else { suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.IYAR)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.IYAN)); } return suffixes; } private List<PopupKeyCandidate> getCandidatesForO() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate(MongolCode.Uni.VERTICAL_RIGHT_ANGLE_BRACKET)); return candidates; } if (isIsolateOrInitial()) { candidates.add(new PopupKeyCandidate(MongolCode.Uni.O)); } else { PopupKeyCandidate medial_U_FVS1 = new PopupKeyCandidate( "" + MongolCode.Uni.U + MongolCode.Uni.FVS1, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.U + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ, "" + MongolCode.Uni.U + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ); candidates.add(medial_U_FVS1); PopupKeyCandidate final_U_FVS1 = new PopupKeyCandidate( "" + MongolCode.Uni.U + MongolCode.Uni.FVS1, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.U + MongolCode.Uni.FVS1); candidates.add(final_U_FVS1); } if (shouldShowSuffixesInPopup()) { candidates.addAll(getSuffixForKeyO()); } return candidates; } private List<PopupKeyCandidate> getSuffixForKeyO() { List<PopupKeyCandidate> suffixes = new ArrayList<>(); if (mKeyboardListener == null) return suffixes; String previousWord = mKeyboardListener.getPreviousMongolWord(true); MongolCode.Gender gender = MongolCode.getWordGender(previousWord); if (gender == MongolCode.Gender.FEMININE) { suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.UEN)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.UED)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.UEUE)); } else { suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.UN)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.UD)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.UU)); } return suffixes; } private List<PopupKeyCandidate> getCandidatesForU() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_ELLIPSIS)); candidates.add(new PopupKeyCandidate(MongolCode.Uni.REFERENCE_MARK)); candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_FOUR_DOTS)); return candidates; } if (isIsolateOrInitial()) { candidates.add(new PopupKeyCandidate(MongolCode.Uni.OE)); candidates.add(new PopupKeyCandidate("" + MongolCode.Uni.UE + MongolCode.Uni.FVS1)); return candidates; } PopupKeyCandidate medial_UE_FVS1 = new PopupKeyCandidate( "" + MongolCode.Uni.UE + MongolCode.Uni.FVS1, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.UE + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ, "" + MongolCode.Uni.UE + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ); candidates.add(medial_UE_FVS1); PopupKeyCandidate medial_UE_FVS2 = new PopupKeyCandidate( "" + MongolCode.Uni.UE + MongolCode.Uni.FVS2, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.UE + MongolCode.Uni.FVS2 + MongolCode.Uni.ZWJ, "" + MongolCode.Uni.UE + MongolCode.Uni.FVS2 + MongolCode.Uni.ZWJ); candidates.add(medial_UE_FVS2); PopupKeyCandidate final_UE_FVS1 = new PopupKeyCandidate( "" + MongolCode.Uni.UE + MongolCode.Uni.FVS1, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.UE + MongolCode.Uni.FVS1); candidates.add(final_UE_FVS1); return candidates; } private List<PopupKeyCandidate> getCandidatesForNA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate("①")); candidates.add(new PopupKeyCandidate("⑪")); candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_DIGIT_ONE)); return candidates; } candidates.add(new PopupKeyCandidate(MongolCode.Uni.ANG)); if (!isIsolateOrInitial()) { // only(?) way to override dotted N before vowel in Unicode 10.0 PopupKeyCandidate na_zwj = new PopupKeyCandidate( "" + MongolCode.Uni.NA + MongolCode.Uni.ZWJ, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.NA + MongolCode.Uni.ZWJ); candidates.add(na_zwj); PopupKeyCandidate na_fvs1 = new PopupKeyCandidate( "" + MongolCode.Uni.NA + MongolCode.Uni.FVS1, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.NA + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ, "" + MongolCode.Uni.NA + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ); candidates.add(na_fvs1); } if (shouldShowSuffixesInPopup()) { candidates.addAll(getSuffixForKeyNA()); } return candidates; } private List<PopupKeyCandidate> getSuffixForKeyNA() { List<PopupKeyCandidate> suffixes = new ArrayList<>(); if (mKeyboardListener == null) return suffixes; String previousWord = mKeyboardListener.getPreviousMongolWord(true); MongolCode.Gender gender = MongolCode.getWordGender(previousWord); if (gender == MongolCode.Gender.FEMININE) { suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.UE)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.NUEGUED)); } else if (gender == MongolCode.Gender.MASCULINE) { suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.U)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.NUGUD)); } else { suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.U)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.NUGUD)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.NUEGUED)); } return suffixes; } private List<PopupKeyCandidate> getCandidatesForBA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate("②")); candidates.add(new PopupKeyCandidate("⑫")); candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_DIGIT_TWO)); return candidates; } candidates.add(new PopupKeyCandidate(MongolCode.Uni.PA)); candidates.add(new PopupKeyCandidate(MongolCode.Uni.FA)); if (shouldShowSuffixesInPopup()) { candidates.addAll(getSuffixForKeyBA()); } return candidates; } private List<PopupKeyCandidate> getSuffixForKeyBA() { List<PopupKeyCandidate> suffixes = new ArrayList<>(); if (mKeyboardListener == null) return suffixes; String previousWord = mKeyboardListener.getPreviousMongolWord(true); MongolCode.Gender gender = MongolCode.getWordGender(previousWord); if (gender == MongolCode.Gender.FEMININE) { suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.BER)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.BEN)); } else { suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.BAR)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.BAN)); } return suffixes; } private List<PopupKeyCandidate> getCandidatesForQA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate("③")); candidates.add(new PopupKeyCandidate("⑬")); candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_DIGIT_THREE)); return candidates; } candidates.add(new PopupKeyCandidate(MongolCode.Uni.HAA)); return candidates; } private List<PopupKeyCandidate> getCandidatesForGA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate("④")); candidates.add(new PopupKeyCandidate("⑭")); candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_DIGIT_FOUR)); return candidates; } candidates.add(new PopupKeyCandidate(MongolCode.Uni.KA)); if (isIsolateOrInitial()) { return candidates; } // see note on MongolCode(FINA_GA_FVS1) PopupKeyCandidate ga_fvs1 = new PopupKeyCandidate( "" + MongolCode.Uni.GA + MongolCode.Uni.FVS1, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.GA + MongolCode.Uni.FVS1); candidates.add(ga_fvs1); // see note on MongolCode(FINA_GA_FVS2) PopupKeyCandidate ga_fvs2 = new PopupKeyCandidate( "" + MongolCode.Uni.GA + MongolCode.Uni.FVS2, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.GA + MongolCode.Uni.FVS2); candidates.add(ga_fvs2); PopupKeyCandidate medi_ga_fvs3 = new PopupKeyCandidate( "" + MongolCode.Uni.GA + MongolCode.Uni.FVS3, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.GA + MongolCode.Uni.FVS3 + MongolCode.Uni.ZWJ, "" + MongolCode.Uni.GA + MongolCode.Uni.FVS3 + MongolCode.Uni.ZWJ); candidates.add(medi_ga_fvs3); return candidates; } private List<PopupKeyCandidate> getCandidatesForMA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate("⑤")); candidates.add(new PopupKeyCandidate("⑮")); candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_DIGIT_FIVE)); return candidates; } return candidates; } private List<PopupKeyCandidate> getCandidatesForLA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_BIRGA)); candidates.add(new PopupKeyCandidate("~")); return candidates; } candidates.add(new PopupKeyCandidate(MongolCode.Uni.LHA)); return candidates; } private List<PopupKeyCandidate> getCandidatesForSA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate("⑥")); candidates.add(new PopupKeyCandidate("⑯")); candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_DIGIT_SIX)); return candidates; } candidates.add(new PopupKeyCandidate(MongolCode.Uni.SHA)); return candidates; } private List<PopupKeyCandidate> getCandidatesForTADA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate("⑦")); candidates.add(new PopupKeyCandidate("⑰")); candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_DIGIT_SEVEN)); return candidates; } if (isIsolateOrInitial()) { char prevChar = getPreviousChar(); String unicode; if (prevChar == MongolCode.Uni.NNBS) { unicode = "" + MongolCode.Uni.DA; } else { unicode = "" + MongolCode.Uni.DA + MongolCode.Uni.FVS1; } PopupKeyCandidate initial_da = new PopupKeyCandidate( unicode, "" + MongolCode.Uni.DA + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ); candidates.add(initial_da); // TODO if this turns out to be an isolate then the FVS1 should be removed } else { PopupKeyCandidate medial_ta_fvs1 = new PopupKeyCandidate( "" + MongolCode.Uni.TA + MongolCode.Uni.FVS1, "" + MongolCode.Uni.MONGOLIAN_NIRUGU + MongolCode.Uni.TA + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ, "" + MongolCode.Uni.TA + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ); candidates.add(medial_ta_fvs1); PopupKeyCandidate final_ta = new PopupKeyCandidate( "" + MongolCode.Uni.TA, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.TA); candidates.add(final_ta); PopupKeyCandidate final_da_fvs1 = new PopupKeyCandidate( "" + MongolCode.Uni.DA + MongolCode.Uni.FVS1, "" + MongolCode.Uni.ZWJ + MongolCode.Uni.DA + MongolCode.Uni.FVS1); candidates.add(final_da_fvs1); } if (shouldShowSuffixesInPopup()) { candidates.addAll(getSuffixForKeyTADA()); } return candidates; } private List<PopupKeyCandidate> getSuffixForKeyTADA() { List<PopupKeyCandidate> suffixes = new ArrayList<>(); if (mKeyboardListener == null) return suffixes; String previousWord = mKeyboardListener.getPreviousMongolWord(true); MongolCode.Gender gender = MongolCode.getWordGender(previousWord); // there were too many choices when there is no context // so I'm removing the ones that can be entered without // any special formatting characters if (gender == null) { //suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.TU)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.DU)); //suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.TAI)); //suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.TAGAN)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.DAGAN)); //suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.TEGEN)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.DEGEN)); suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.DAQI)); //suffixes.add(new PopupKeyCandidate(MongolCode.Suffix.TAQI)); return suffixes; } char lastChar = previousWord.charAt(previousWord.length() - 1); String tuDu = MongolCode.getSuffixTuDu(gender, lastChar); suffixes.add(new PopupKeyCandidate(tuDu)); String taiTei = MongolCode.getSuffixTaiTei(gender); suffixes.add(new PopupKeyCandidate(taiTei)); String taganDagan = MongolCode.getSuffixTaganDagan(gender, lastChar); suffixes.add(new PopupKeyCandidate(taganDagan)); String taqiDaqi = MongolCode.getSuffixTaqiDaqi(gender, lastChar); suffixes.add(new PopupKeyCandidate(taqiDaqi)); return suffixes; } private List<PopupKeyCandidate> getCandidatesForCHA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate("⑧")); candidates.add(new PopupKeyCandidate("⑱")); candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_DIGIT_EIGHT)); return candidates; } candidates.add(new PopupKeyCandidate(MongolCode.Uni.ZA)); candidates.add(new PopupKeyCandidate(MongolCode.Uni.TSA)); candidates.add(new PopupKeyCandidate(MongolCode.Uni.CHI)); return candidates; } private List<PopupKeyCandidate> getCandidatesForJA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate("⑨")); candidates.add(new PopupKeyCandidate("⑲")); candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_DIGIT_NINE)); return candidates; } candidates.add(new PopupKeyCandidate(MongolCode.Uni.ZHI)); return candidates; } private List<PopupKeyCandidate> getCandidatesForYA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate("⓪")); candidates.add(new PopupKeyCandidate("⑩")); candidates.add(new PopupKeyCandidate("⑳")); candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_DIGIT_ZERO)); return candidates; } candidates.add(new PopupKeyCandidate(MongolCode.Uni.WA)); if (isIsolateOrInitial()) { PopupKeyCandidate initial_YA_FVS1 = new PopupKeyCandidate( "" + MongolCode.Uni.YA + MongolCode.Uni.FVS1, "" + MongolCode.Uni.YA + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ, "" + MongolCode.Uni.YA + MongolCode.Uni.FVS1 + MongolCode.Uni.ZWJ); candidates.add(initial_YA_FVS1); return candidates; } return candidates; } private List<PopupKeyCandidate> getCandidatesForRA() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_COLON)); candidates.add(new PopupKeyCandidate(MongolCode.Uni.VERTICAL_SEMICOLON)); candidates.add(new PopupKeyCandidate(MongolCode.Uni.DOUBLE_QUESTION_MARK)); candidates.add(new PopupKeyCandidate(MongolCode.Uni.EXCLAMATION_QUESTION_MARK)); candidates.add(new PopupKeyCandidate(MongolCode.Uni.DOUBLE_EXCLAMATION_MARK)); return candidates; } candidates.add(new PopupKeyCandidate(MongolCode.Uni.ZRA)); return candidates; } private List<PopupKeyCandidate> getCandidatesForComma() { List<PopupKeyCandidate> candidates = new ArrayList<>(); if (mIsShowingPunctuation) { candidates.add(new PopupKeyCandidate("-", false)); candidates.add(new PopupKeyCandidate("+", false)); candidates.add(new PopupKeyCandidate("=", false)); return candidates; } candidates.add(new PopupKeyCandidate(MongolCode.Uni.VERTICAL_QUESTION_MARK)); candidates.add(new PopupKeyCandidate(MongolCode.Uni.MONGOLIAN_FULL_STOP)); candidates.add(new PopupKeyCandidate(MongolCode.Uni.VERTICAL_EXCLAMATION_MARK)); return candidates; } private List<PopupKeyCandidate> getCandidatesForSpace() { List<PopupKeyCandidate> candidates = new ArrayList<>(); PopupKeyCandidate nnbs; if (hasCandidatesView()) { nnbs = new PopupKeyCandidate( "" + MongolCode.Uni.NNBS, KEY_SPACE_SUB_DISPLAY); } else { nnbs = new PopupKeyCandidate( "" + MongolCode.Uni.NNBS, KEY_SPACE_SUB_DISPLAY, " "); } candidates.add(nnbs); return candidates; } @Override public String getDisplayName() { if (mDisplayName == null) return DEFAULT_DISPLAY_NAME; return mDisplayName; } @Override public void onKeyboardKeyClick() { mIsShowingPunctuation = !mIsShowingPunctuation; if (mIsShowingPunctuation) { setPunctuationKeyValues(); } else { setKeyValues(); } } @Override public void onKeyInput(String text) { // TA/DA defaults to DA except in the INITIAL location if (text.equals(String.valueOf(MongolCode.Uni.DA))) { char prevChar = getPreviousChar(); if (!MongolCode.isMongolian(prevChar)) { text = String.valueOf(MongolCode.Uni.TA); } } super.onKeyInput(text); } }
/** * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.emm.agent.utils; import org.wso2.emm.agent.R; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.widget.EditText; import android.widget.LinearLayout; /** * The CommonDialogUtils class contains the all dialog templates. */ public abstract class CommonDialogUtils { /** * Return an Alert Dialog with one button. * @param context - The Activity which needs this alert dialog. * @param message - The message in the alert. * @param positiveBtnLabel - The label of the positive button. * @param positiveClickListener- The onClickListener of the positive button. * @return - The generated Alert Dialog. */ public static AlertDialog.Builder getAlertDialogWithOneButton(Context context, String message, String positiveBtnLabel, DialogInterface.OnClickListener positiveClickListener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(message).setPositiveButton(positiveBtnLabel, positiveClickListener); return builder; } /** * Return an Alert Dialog with two buttons. * @param context - The Activity which needs this alert dialog. * @param message - The message in the alert. * @param positiveBtnLabel - The label of the positive button. * @param negetiveBtnLabel - The label of the negative button. * @param positiveClickListener- The onClickListener of the positive button. * @param negativeClickListener- The onClickListener of the negative button. * @return - The generated Alert Dialog. */ public static AlertDialog.Builder getAlertDialogWithTwoButton(Context context, String message, String positiveBtnLabel, String negetiveBtnLabel, DialogInterface.OnClickListener positiveClickListener, DialogInterface.OnClickListener negativeClickListener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(message).setPositiveButton(positiveBtnLabel, positiveClickListener) .setNegativeButton(negetiveBtnLabel, negativeClickListener); return builder; } /** * Shows the Network unavailable message. * @param context - The Activity where checking the network availability. */ public static void showNetworkUnavailableMessage(Context context) { AlertDialog.Builder builder = CommonDialogUtils.getAlertDialogWithOneButton(context, context.getResources() .getString( R.string.error_network_unavailable), context.getResources() .getString(R.string.button_ok), null ); builder.show(); } /** * Return an Alert Dialog with two buttons and a title. * @param context - The Activity which needs this alert dialog. * @param title - The title of the message. * @param message - The message in the alert. * @param positiveBtnLabel - The label of the positive button. * @param negetiveBtnLabel - The label of the negative button. * @param positiveClickListener- The onClickListener of the positive button. * @param negativeClickListener- The onClickListener of the negative button. * @return - The generated Alert Dialog. */ public static AlertDialog.Builder getAlertDialogWithTwoButtonAndTitle(Context context, String title, String message, String positiveBtnLabel, String negetiveBtnLabel, DialogInterface.OnClickListener positiveClickListener, DialogInterface.OnClickListener negativeClickListener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(title); builder.setMessage(message).setPositiveButton(positiveBtnLabel, positiveClickListener) .setNegativeButton(negetiveBtnLabel, negativeClickListener); return builder; } /** * Returns an Alert Dialog with one button and title. * @param context -The activity which need this alert. * @param title -The alert title. * @param message -The alert message. * @param positiveBtnLabel -The positive button label. * @param positiveClickListener -The positive button listener. * @return - An alert dialog. */ public static AlertDialog.Builder getAlertDialogWithOneButtonAndTitle(Context context, String title, String message, String positiveBtnLabel, DialogInterface.OnClickListener positiveClickListener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(title); builder.setMessage(message).setPositiveButton(positiveBtnLabel, positiveClickListener); builder.show(); return builder; } /** * Returns an Alert Dialog with OK button and title. * @param context -The activity which need this alert. * @param title -The alert title. * @param message -The alert message. * @param neutralBtnLabel -The Neutral button label. * @param neutralClickListener -The neutral button listener. * @return - An alert dialog. */ public static AlertDialog.Builder getAlertDialogWithNeutralButtonAndTitle(Context context, String title, String message, String neutralBtnLabel, DialogInterface.OnClickListener neutralClickListener) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(title); builder.setMessage(message).setNeutralButton(neutralBtnLabel, neutralClickListener); builder.show(); return builder; } /** * Shows the ProgressDialog. * * @param context -The Activity which needs the ProgressDialog. * @param title -The title. * @param message -The message. * @param cancelListener -The OnCancelListener. * @return - A progress dialog. */ public static ProgressDialog showProgressDialog(Context context, String title, String message, OnCancelListener cancelListener) { ProgressDialog progressDialog = ProgressDialog.show(context, title, message, true); progressDialog.setCancelable(true); progressDialog.setOnCancelListener(cancelListener); return progressDialog; } /** * Stops progressDialog. * @param progressDialog -Progress dialog which needs to be stopped. */ public static void stopProgressDialog(ProgressDialog progressDialog) { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } /** * * Return an Alert Dialog with two buttons and a title. * @param context - The Activity which needs this alert dialog. * @param message - The message in the alert. * @param positiveBtnLabel - The label of the positive button. * @param negetiveBtnLabel - The label of the negative button. * @param positiveClickListener- The onClickListener of the positive button. * @param negativeClickListener- The onClickListener of the negative button. * @param input - Edit text input. * @return - The generated Alert Dialog. */ public static AlertDialog.Builder getAlertDialogWithTwoButtonAndEditView(Context context, String message, String positiveBtnLabel, String negetiveBtnLabel, DialogInterface.OnClickListener positiveClickListener, DialogInterface.OnClickListener negativeClickListener, EditText input) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(message).setPositiveButton(positiveBtnLabel, positiveClickListener) .setNegativeButton(negetiveBtnLabel, negativeClickListener); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); input.setLayoutParams(params); builder.setView(input); return builder; } }
// 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.cloud.hypervisor.vmware; import org.apache.cloudstack.api.InternalIdentity; import com.cloud.org.Grouping; public interface VmwareDatacenterZoneMap extends Grouping, InternalIdentity { public long getId(); public long getZoneId(); public long getVmwareDcId(); }
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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.gravitee.gateway.reactor.handler; import io.gravitee.gateway.reactor.Reactable; import io.gravitee.gateway.reactor.handler.impl.DefaultReactorHandlerRegistry; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.Arrays; import java.util.List; import java.util.Set; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ReactorHandlerRegistryTest { @InjectMocks private DefaultReactorHandlerRegistry reactorHandlerRegistry; @Mock private ReactorHandlerFactoryManager reactorHandlerFactoryManager; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @Test public void shouldHaveOneEntrypoint() { Reactable reactable = createReactable("reactable1", "/"); ReactorHandler handler = createReactorHandler(reactable); when(reactorHandlerFactoryManager.create(reactable)).thenReturn(handler); reactorHandlerRegistry.create(reactable); Assert.assertEquals(1, reactorHandlerRegistry.getEntrypoints().size()); } @Test public void shouldHaveTwoEntrypoints_singleReactable() { Reactable reactable = createReactable("reactable1", new VirtualHost("/products/v1"), new VirtualHost("/products/v2")); ReactorHandler handler = createReactorHandler(reactable); when(reactorHandlerFactoryManager.create(reactable)).thenReturn(handler); reactorHandlerRegistry.create(reactable); Assert.assertEquals(2, reactorHandlerRegistry.getEntrypoints().size()); } @Test public void shouldHaveTwoEntrypoints_singleReactable_withVirtualHost() { Reactable reactable = createReactable("reactable1", new VirtualHost("/products/v1"), new VirtualHost("api.gravitee.io", "/products/v2")); ReactorHandler handler = createReactorHandler(reactable); when(reactorHandlerFactoryManager.create(reactable)).thenReturn(handler); reactorHandlerRegistry.create(reactable); Assert.assertEquals(2, reactorHandlerRegistry.getEntrypoints().size()); Assert.assertEquals("/products/v2/", reactorHandlerRegistry.getEntrypoints().iterator().next().path()); } @Test public void shouldHaveTwoEntrypoints_duplicateContextPath() { Reactable reactable = createReactable("reactable1","/"); ReactorHandler handler = createReactorHandler(reactable); when(reactorHandlerFactoryManager.create(reactable)).thenReturn(handler); reactorHandlerRegistry.create(reactable); Reactable reactable2 = createReactable("reactable1","/"); ReactorHandler handler2 = createReactorHandler(reactable2); when(reactorHandlerFactoryManager.create(reactable2)).thenReturn(handler2); reactorHandlerRegistry.create(reactable2); Assert.assertEquals(2, reactorHandlerRegistry.getEntrypoints().size()); } @Test public void shouldHaveTwoEntrypoints() { Reactable reactable = createReactable("reactable1","/"); ReactorHandler handler = createReactorHandler(reactable); when(reactorHandlerFactoryManager.create(reactable)).thenReturn(handler); reactorHandlerRegistry.create(reactable); Reactable reactable2 = createReactable("reactable1","/products"); ReactorHandler handler2 = createReactorHandler(reactable2); when(reactorHandlerFactoryManager.create(reactable2)).thenReturn(handler2); reactorHandlerRegistry.create(reactable2); Assert.assertEquals(2, reactorHandlerRegistry.getEntrypoints().size()); Assert.assertEquals("/products/", reactorHandlerRegistry.getEntrypoints().iterator().next().path()); } @Test public void shouldHaveTwoEntrypoints_duplicateContextPath_withVirtualHost() { Reactable reactable = createReactable("reactable1","/"); ReactorHandler handler = createReactorHandler(reactable); when(reactorHandlerFactoryManager.create(reactable)).thenReturn(handler); reactorHandlerRegistry.create(reactable); Reactable reactable2 = createReactable("reactable1","api.gravitee.io", "/"); ReactorHandler handler2 = createReactorHandler(reactable2); when(reactorHandlerFactoryManager.create(reactable2)).thenReturn(handler2); reactorHandlerRegistry.create(reactable2); Assert.assertEquals(2, reactorHandlerRegistry.getEntrypoints().size()); Assert.assertEquals("/", reactorHandlerRegistry.getEntrypoints().iterator().next().path()); } @Test public void shouldHaveTwoEntrypoints_updateReactable() { DummyReactable reactable = createReactable("reactable1","/"); ReactorHandler handler = createReactorHandler(reactable); when(reactorHandlerFactoryManager.create(reactable)).thenReturn(handler); reactorHandlerRegistry.create(reactable); DummyReactable updateReactable = createReactable("reactable2","api.gravitee.io", "/"); ReactorHandler handler2 = createReactorHandler(updateReactable); when(reactorHandlerFactoryManager.create(updateReactable)).thenReturn(handler2); reactorHandlerRegistry.update(updateReactable); Assert.assertEquals(2, reactorHandlerRegistry.getEntrypoints().size()); } @Test public void shouldHaveOneEntrypoint_updateSameReactable() { DummyReactable reactable = createReactable("reactable1","/"); ReactorHandler handler = createReactorHandler(reactable); when(reactorHandlerFactoryManager.create(reactable)).thenReturn(handler); reactorHandlerRegistry.create(reactable); DummyReactable updateReactable = createReactable("reactable1","api.gravitee.io", "/new-path"); ReactorHandler handler2 = createReactorHandler(updateReactable); when(reactorHandlerFactoryManager.create(updateReactable)).thenReturn(handler2); reactorHandlerRegistry.update(updateReactable); Assert.assertEquals(1, reactorHandlerRegistry.getEntrypoints().size()); Assert.assertEquals("/new-path/", reactorHandlerRegistry.getEntrypoints().get(0).path()); } @Test public void shouldHaveOneEntrypoint_removeSameReactable() { DummyReactable reactable = createReactable("reactable1","/"); ReactorHandler handler = createReactorHandler(reactable); when(reactorHandlerFactoryManager.create(reactable)).thenReturn(handler); reactorHandlerRegistry.create(reactable); DummyReactable updateReactable = createReactable("reactable1","/"); reactorHandlerRegistry.remove(updateReactable); Assert.assertEquals(0, reactorHandlerRegistry.getEntrypoints().size()); } private DummyReactable createReactable(String id, VirtualHost ... virtualHosts) { return new DummyReactable(id, Arrays.asList(virtualHosts)); } private DummyReactable createReactable(String id, String contextPath) { return createReactable(id, null, contextPath); } private DummyReactable createReactable(String id, String virtualHost, String contextPath) { return createReactable(id, new VirtualHost(virtualHost, contextPath)); } private ReactorHandler createReactorHandler(Reactable reactable) { ReactorHandler handler = mock(ReactorHandler.class); when(handler.reactable()).thenReturn(reactable); return handler; } private class DummyReactable implements Reactable { private final String id; private final List<Entrypoint> entrypoints; public DummyReactable(String id, List<Entrypoint> entrypoints) { this.id = id; this.entrypoints = entrypoints; } @Override public int hashCode() { return id.hashCode(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DummyReactable that = (DummyReactable) o; return id.equals(that.id); } @Override public boolean enabled() { return false; } @Override public <D> Set<D> dependencies(Class<D> type) { return null; } @Override public List<Entrypoint> entrypoints() { return entrypoints; } } }
package com.jiangdg.usbcamera.utils; /* * libcommon * utility/helper classes for myself * * Copyright (c) 2014-2018 saki t_saki@serenegiant.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. */ import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; public class HandlerThreadHandler extends Handler { private static final String TAG = "HandlerThreadHandler"; public static final HandlerThreadHandler createHandler() { return createHandler(TAG); } public static final HandlerThreadHandler createHandler(final String name) { final HandlerThread thread = new HandlerThread(name); thread.start(); return new HandlerThreadHandler(thread.getLooper()); } public static final HandlerThreadHandler createHandler(final Callback callback) { return createHandler(TAG, callback); } public static final HandlerThreadHandler createHandler(final String name, final Callback callback) { final HandlerThread thread = new HandlerThread(name); thread.start(); return new HandlerThreadHandler(thread.getLooper(), callback); } private HandlerThreadHandler(final Looper looper) { super(looper); } private HandlerThreadHandler(final Looper looper, final Callback callback) { super(looper, callback); } }
package dev.bug.api.data.mos.repositories; import dev.bug.api.data.mos.model.Category; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface CategoryRepository extends CrudRepository<Category, Long> { Category findByCategoryId(Long categoryId); }
/* * Copyright 2020 ConsenSys AG. * * 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 tech.pegasys.teku.validator.client.metrics; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import tech.pegasys.teku.metrics.StubMetricsSystem; import tech.pegasys.teku.metrics.TekuMetricCategory; import tech.pegasys.teku.validator.client.metrics.BeaconChainRequestCounter.RequestOutcome; class BeaconChainRequestCounterTest { public static final String METRIC_NAME = "metricName"; private final StubMetricsSystem metricsSystem = new StubMetricsSystem(); private final BeaconChainRequestCounter counter = BeaconChainRequestCounter.create(metricsSystem, METRIC_NAME, "Some help"); @Test public void shouldIncrementSuccessCounter() { counter.onSuccess(); assertThat(getValue(RequestOutcome.SUCCESS)).isEqualTo(1); assertThat(getValue(RequestOutcome.ERROR)).isZero(); assertThat(getValue(RequestOutcome.DATA_UNAVAILABLE)).isZero(); } @Test public void shouldIncrementErrorCounter() { counter.onError(); assertThat(getValue(RequestOutcome.ERROR)).isEqualTo(1); assertThat(getValue(RequestOutcome.SUCCESS)).isZero(); assertThat(getValue(RequestOutcome.DATA_UNAVAILABLE)).isZero(); } @Test public void shouldIncrementDataUnavailableCounter() { counter.onDataUnavailable(); assertThat(getValue(RequestOutcome.DATA_UNAVAILABLE)).isEqualTo(1); assertThat(getValue(RequestOutcome.ERROR)).isZero(); assertThat(getValue(RequestOutcome.SUCCESS)).isZero(); } private long getValue(final RequestOutcome requestOutcome) { return metricsSystem .getCounter(TekuMetricCategory.VALIDATOR, METRIC_NAME) .getValue(requestOutcome.name()); } }
// Flipping an Image // URL : https://leetcode.com/problems/flipping-an-image/ package com.akshat; public class FlipImage { public static void main(String[] args) { int[][] image = { {1, 1, 0}, {1, 0, 1}, {0, 0, 0} }; System.out.println(flipAndInvertImage(image)); } static int[][] flipAndInvertImage(int[][] image){ for (int[] row : image){ for (int i=0; i< (image[0].length+1)/2; i++){ int temp = row[i]^1; row[i] = row[image[0].length - i - 1] ^ 1; row[image[0].length - i - 1] = temp; } } return image; } }
package de.timmi6790.mpstats.api.client.common.leaderboard.deserializers; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import de.timmi6790.mpstats.api.client.common.leaderboard.exceptions.InvalidLeaderboardCombinationRestException; import de.timmi6790.mpstats.api.client.common.leaderboard.models.Leaderboard; import de.timmi6790.mpstats.api.client.exception.BaseRestException; import java.io.IOException; import java.io.Serial; import java.util.ArrayList; import java.util.List; public class InvalidLeaderboardCombinationRestExceptionDeserializer extends StdDeserializer<InvalidLeaderboardCombinationRestException> { @Serial private static final long serialVersionUID = 3342025404018887507L; public InvalidLeaderboardCombinationRestExceptionDeserializer() { super(InvalidLeaderboardCombinationRestException.class); } @Override public InvalidLeaderboardCombinationRestException deserialize(final JsonParser jsonParser, final DeserializationContext ctxt) throws IOException { final JsonNode node = jsonParser.getCodec().readTree(jsonParser); final BaseRestException baseException = ctxt.readValue(node.traverse(jsonParser.getCodec()), BaseRestException.class); final List<Leaderboard> suggestedLeaderboards = new ArrayList<>(); for (final JsonNode subNodes : node.findValue("suggestedLeaderboards")) { final Leaderboard leaderboard = ctxt.readValue(subNodes.traverse(jsonParser.getCodec()), Leaderboard.class); suggestedLeaderboards.add(leaderboard); } return new InvalidLeaderboardCombinationRestException( baseException, suggestedLeaderboards ); } }
package model.graphics.object; import controllers.scene.RayTracer; import exceptions.PointOutOfRangeException; import model.graphics.LocalGeo; import model.graphics.Ray; import model.math.Normal; import model.math.Point; import model.math.Vector; import model.math.transformation.Identity; import model.math.transformation.Matrix; /** * @author Abdullah Emad * This class represents a sphere in the world. A sphere is represented * by the coordinates of its center and the length of its radius * The Sphere class implements the Shape interface */ public class Sphere implements Shape { /** * the lighting material of the sphere */ private BRDF brdf; /** * the center location of the sphere */ private Point center; /** * the radius of the sphere */ private double radius; private Matrix transformMatrix; /** * * @param center the center * @param radius the radius * @param brdf the brdf colors */ public Sphere(Point center, double radius, BRDF brdf) { this.center = center; this.radius = radius; this.brdf = brdf; this.transformMatrix = new Identity(); } @Override public LocalGeo intersect(Ray ray) throws PointOutOfRangeException { //transform the ray Matrix invTranform = this.transformMatrix.invert(); Ray originalRay = ray; ray = ray.transform(invTranform); Point p0 = ray.getPos(); Vector p1 = ray.getDir(); Vector p0_c = p0.subtract(this.center); double a = p1.dot(p1); double b = 2.0 * p1.dot(p0_c); double c = p0_c.dot(p0_c) - Math.pow(this.radius, 2.0); double disc = Math.pow(b, 2.0) - (4.0 * a * c); // no Intersection possible if(disc < 0.0){ throw new PointOutOfRangeException(); } double x1 = (-b + Math.sqrt(disc)) / (2.0 * a); double x2 = (-b - Math.sqrt(disc)) / (2.0 * a); if(x1 < 0 && x2 < 0) { throw new PointOutOfRangeException(); } double t; if(x1 < 0){ t = x2; } else if(x2 < 0) { t = x1; } else { t = Double.min(x1, x2); } // Transform the Pos, it's normal and the ray by the transformMatrix Point pos = ray.ray(t); Normal normal = pos.subtract(center).normalize(); pos = this.transformMatrix.transform(pos); normal = this.transformMatrix.transform(normal).normalize(); t = originalRay.calculateT(pos); return new LocalGeo(t, pos, normal); } @Override public boolean doesIntersect(Ray ray) { try{ intersect(ray); } catch (PointOutOfRangeException e) { return false; } return true; } @Override public void transform(Matrix matrix) { this.transformMatrix = matrix.multiply(this.transformMatrix); } @Override public BRDF getBRDF() { return this.brdf; } @Override public Box calculateBoundingBox() { Point A = new Point(this.center.getX() - radius - RayTracer.ERROR_EPSILON, this.center.getY() - radius - RayTracer.ERROR_EPSILON, this.center.getZ() - radius - RayTracer.ERROR_EPSILON); Point B = new Point(this.center.getX() + radius + RayTracer.ERROR_EPSILON, this.center.getY() + radius + RayTracer.ERROR_EPSILON, this.center.getZ() + radius + RayTracer.ERROR_EPSILON); return new Box(A, B); } @Override public boolean isOverlapping(Box boundingBox) { Box box = calculateBoundingBox(); return box.isOverlapping(boundingBox); } }
/* * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /** * 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.sun.org.apache.xml.internal.security.utils; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Purpose of this class is to enable the XML Parser to keep track of ID * attributes. This is done by 'registering' attributes of type ID at the * IdResolver. * @deprecated */ @Deprecated public class IdResolver { private IdResolver() { // we don't allow instantiation } /** * Method registerElementById * * @param element the element to register * @param id the ID attribute */ public static void registerElementById(Element element, Attr id) { element.setIdAttributeNode(id, true); } /** * Method getElementById * * @param doc the document * @param id the value of the ID * @return the element obtained by the id, or null if it is not found. */ public static Element getElementById(Document doc, String id) { return doc.getElementById(id); } }
package com.daop.msc.order.lb; import org.springframework.cloud.client.ServiceInstance; import org.springframework.stereotype.Component; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * @BelongsProject: spring_cloud_learn * @BelongsPackage: com.daop.msc.ribbonrule * @Description: * @DATE: 2020-10-21 * @AUTHOR: Administrator **/ @Component public class MyLB implements LoadBalance { private AtomicInteger atomicInteger = new AtomicInteger(0); @Override public ServiceInstance instances(List<ServiceInstance> serviceInstances) { int index = getAndIncrement() % serviceInstances.size(); return serviceInstances.get(index); } public final int getAndIncrement() { int current; int next; do { current = this.atomicInteger.get(); next = current >= Integer.MAX_VALUE ? 0 : (current + 1); } while (!this.atomicInteger.compareAndSet(current, next)); System.out.println("*****第几次访问next: " + next); return next; } }
package me.rojetto.comfy.tree; import me.rojetto.comfy.ArgumentType; import me.rojetto.comfy.CommandContext; import me.rojetto.comfy.exception.CommandTreeException; import java.util.List; public class Argument extends CommandNode<Argument> { private final String name; private final ArgumentType type; public Argument(String name, ArgumentType type) { this.name = name; this.type = type; if(!name.matches("[A-Za-z0-9]+")) { throw new CommandTreeException("Argument names can only contain alphanumeric characters."); } } public String getName() { return name; } public ArgumentType getType() { return type; } @Override public boolean matches(String segment) { return type.matches(segment); } @Override public List<String> getSuggestions(CommandContext context) { return type.getSuggestions(context); } @Override public String toString() { if(isOptional()) { return "<" + name + ">"; } else { return "[" + name + "]"; } } }
/* * Copyright 2016-2021 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.lexmodelsv2.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.lexmodelsv2.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * BuiltInSlotTypeSummaryMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class BuiltInSlotTypeSummaryMarshaller { private static final MarshallingInfo<String> SLOTTYPESIGNATURE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("slotTypeSignature").build(); private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("description").build(); private static final BuiltInSlotTypeSummaryMarshaller instance = new BuiltInSlotTypeSummaryMarshaller(); public static BuiltInSlotTypeSummaryMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(BuiltInSlotTypeSummary builtInSlotTypeSummary, ProtocolMarshaller protocolMarshaller) { if (builtInSlotTypeSummary == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(builtInSlotTypeSummary.getSlotTypeSignature(), SLOTTYPESIGNATURE_BINDING); protocolMarshaller.marshall(builtInSlotTypeSummary.getDescription(), DESCRIPTION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
/** * Copyright 2014 Netflix, 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 rx.internal.operators; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import rx.Observable; import rx.Observable.Operator; import rx.Subscription; import rx.functions.Action0; import rx.subscriptions.Subscriptions; import rx.Observer; import rx.Subscriber; /** * Creates windows of values into the source sequence with skip frequency and size bounds. * * If skip == size then the windows are non-overlapping, otherwise, windows may overlap * or can be discontinuous. The returned Observable sequence is cold and need to be * consumed while the window operation is in progress. * * <p>Note that this conforms the Rx.NET behavior, but does not match former RxJava * behavior, which operated as a regular buffer and mapped its lists to Observables.</p> * * @param <T> the value type */ public final class OperatorWindowWithSize<T> implements Operator<Observable<T>, T> { final int size; final int skip; public OperatorWindowWithSize(int size, int skip) { this.size = size; this.skip = skip; } @Override public Subscriber<? super T> call(Subscriber<? super Observable<T>> child) { if (skip == size) { return new ExactSubscriber(child); } return new InexactSubscriber(child); } /** Subscriber with exact, non-overlapping window bounds. */ final class ExactSubscriber extends Subscriber<T> { final Subscriber<? super Observable<T>> child; int count; BufferUntilSubscriber<T> window; volatile boolean noWindow = true; final Subscription parentSubscription = this; public ExactSubscriber(Subscriber<? super Observable<T>> child) { /** * See https://github.com/ReactiveX/RxJava/issues/1546 * We cannot compose through a Subscription because unsubscribing * applies to the outer, not the inner. */ this.child = child; /* * Add unsubscribe hook to child to get unsubscribe on outer (unsubscribing on next window, not on the inner window itself) */ child.add(Subscriptions.create(new Action0() { @Override public void call() { // if no window we unsubscribe up otherwise wait until window ends if(noWindow) { parentSubscription.unsubscribe(); } } })); } @Override public void onStart() { // no backpressure as we are controlling data flow by window size request(Long.MAX_VALUE); } @Override public void onNext(T t) { if (window == null) { noWindow = false; window = BufferUntilSubscriber.create(); child.onNext(window); } window.onNext(t); if (++count % size == 0) { window.onComplete(); window = null; noWindow = true; if (child.isUnsubscribed()) { parentSubscription.unsubscribe(); return; } } } @Override public void onError(Throwable e) { if (window != null) { window.onError(e); } child.onError(e); } @Override public void onComplete() { if (window != null) { window.onComplete(); } child.onComplete(); } } /** Subscriber with inexact, possibly overlapping or skipping windows. */ final class InexactSubscriber extends Subscriber<T> { final Subscriber<? super Observable<T>> child; int count; final List<CountedSubject<T>> chunks = new LinkedList<CountedSubject<T>>(); final Subscription parentSubscription = this; public InexactSubscriber(Subscriber<? super Observable<T>> child) { /** * See https://github.com/ReactiveX/RxJava/issues/1546 * We cannot compose through a Subscription because unsubscribing * applies to the outer, not the inner. */ this.child = child; /* * Add unsubscribe hook to child to get unsubscribe on outer (unsubscribing on next window, not on the inner window itself) */ child.add(Subscriptions.create(new Action0() { @Override public void call() { // if no window we unsubscribe up otherwise wait until window ends if (chunks == null || chunks.size() == 0) { parentSubscription.unsubscribe(); } } })); } @Override public void onStart() { // no backpressure as we are controlling data flow by window size request(Long.MAX_VALUE); } @Override public void onNext(T t) { if (count++ % skip == 0) { if (!child.isUnsubscribed()) { CountedSubject<T> cs = createCountedSubject(); chunks.add(cs); child.onNext(cs.producer); } } Iterator<CountedSubject<T>> it = chunks.iterator(); while (it.hasNext()) { CountedSubject<T> cs = it.next(); cs.consumer.onNext(t); if (++cs.count == size) { it.remove(); cs.consumer.onComplete(); } } if (chunks.size() == 0 && child.isUnsubscribed()) { parentSubscription.unsubscribe(); return; } } @Override public void onError(Throwable e) { List<CountedSubject<T>> list = new ArrayList<CountedSubject<T>>(chunks); chunks.clear(); for (CountedSubject<T> cs : list) { cs.consumer.onError(e); } child.onError(e); } @Override public void onComplete() { List<CountedSubject<T>> list = new ArrayList<CountedSubject<T>>(chunks); chunks.clear(); for (CountedSubject<T> cs : list) { cs.consumer.onComplete(); } child.onComplete(); } CountedSubject<T> createCountedSubject() { final BufferUntilSubscriber<T> bus = BufferUntilSubscriber.create(); return new CountedSubject<T>(bus, bus); } } /** * Record to store the subject and the emission count. * @param <T> the subject's in-out type */ static final class CountedSubject<T> { final Observer<T> consumer; final Observable<T> producer; int count; public CountedSubject(Observer<T> consumer, Observable<T> producer) { this.consumer = consumer; this.producer = producer; } } }
package net.sentientturtle.discordbot.components.healthcheck; import net.sentientturtle.discordbot.loader.StaticLoaded; import net.sentientturtle.util.Tuple2; import java.util.Collection; import java.util.HashMap; import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Bot health subsystem; Enables classes/objects to register a health-check function */ public class HealthCheck implements StaticLoaded { private static final HashMap<Class<?>, HealthUpdateSupplier> static_map = new HashMap<>(); private static final HashMap<Object, HealthUpdateSupplier> instance_map = new HashMap<>(); public static void addStatic(Class<?> clazz, Supplier<HealthStatus> statusSupplier) { addStatic(clazz, statusSupplier, Optional::empty); } public static void addStatic(Class<?> clazz, Supplier<HealthStatus> statusSupplier, Supplier<Optional<String>> statusMessageSupplier) { static_map.put(clazz, new HealthUpdateSupplier(statusSupplier, statusMessageSupplier)); } public static void addInstance(Object object, Supplier<HealthStatus> statusSupplier) { instance_map.put(object, new HealthUpdateSupplier(statusSupplier, Optional::empty)); } public static void addInstance(Object object, Supplier<HealthStatus> statusSupplier, Supplier<Optional<String>> statusMessageSupplier) { instance_map.put(object, new HealthUpdateSupplier(statusSupplier, statusMessageSupplier)); } public static Collection<String> getMessages() { return Stream.concat( static_map.entrySet().stream().map(entry -> Tuple2.of(entry.getKey().getSimpleName(), entry.getValue())), instance_map.entrySet().stream().map(entry -> Tuple2.of(entry.getKey().getClass().getSimpleName(), entry.getValue())) ).map(tuple -> { assert tuple.one != null && tuple.two != null; var name = tuple.one; var icon = tuple.two.statusSupplier.get().asIcon(); var message = tuple.two.statusMessageSupplier.get(); return String.format("%s %-16s\t%s", icon, name, message.orElse("")); }) .collect(Collectors.toList()); } private static class HealthUpdateSupplier { public Supplier<HealthStatus> statusSupplier; public Supplier<Optional<String>> statusMessageSupplier; public HealthUpdateSupplier(Supplier<HealthStatus> statusSupplier, Supplier<Optional<String>> statusMessageSupplier) { this.statusSupplier = statusSupplier; this.statusMessageSupplier = statusMessageSupplier; } } }
package de.tucottbus.kt.jlab.datadisplays.utils; public class DpiConverter { private double nDpi; private static final double nMmPerInch = 25.4; private static final double nPtPerInch = 72; public DpiConverter(int nDpi) { this.nDpi = (double)nDpi; } public static double mm2inch(double nMm) { return nMm/nMmPerInch; } public static double mm2pt(double nMm) { return nMm/nMmPerInch*nPtPerInch; } public int mm2px(double nMm) { return (int)Math.round(mm2inch(nMm)*nDpi); } public static double inch2mm(double nInch) { return nInch*nMmPerInch; } public static double inch2pt(double nInch) { return nInch*nPtPerInch; } public double inch2px(double nInch) { return nInch*nDpi; } public static double pt2mm(double nPt) { return nPt/nPtPerInch*nMmPerInch; } public static double pt2inch(double nPt) { return nPt/nPtPerInch; } public int pt2px(double nPt) { return (int)Math.round(pt2inch(nPt)*nDpi); } public double px2mm(int nPx) { return (double)nPx/nDpi*nMmPerInch; } public double px2inch(int nPx) { return (double)nPx/nDpi; } public double px2pt(int nPx) { return (double)nPx/nDpi*nPtPerInch; } public double x2y(double nVal, String sUnitIn, String sUnitOut) { if ("mm".equals(sUnitIn)) { if ("mm" .equals(sUnitOut)) return nVal; else if ("inch".equals(sUnitOut)) return mm2inch(nVal); else if ("pt" .equals(sUnitOut)) return mm2pt(nVal); else if ("px" .equals(sUnitOut)) return mm2px(nVal); else return Double.NaN; } else if ("inch".equals(sUnitIn)) { if ("mm" .equals(sUnitOut)) return inch2mm(nVal); else if ("inch".equals(sUnitOut)) return nVal; else if ("pt" .equals(sUnitOut)) return inch2pt(nVal); else if ("px" .equals(sUnitOut)) return inch2px(nVal); else return Double.NaN; } else if ("pt".equals(sUnitIn)) { if ("mm" .equals(sUnitOut)) return pt2mm(nVal); else if ("inch".equals(sUnitOut)) return pt2inch(nVal); else if ("pt" .equals(sUnitOut)) return nVal; else if ("px" .equals(sUnitOut)) return pt2px(nVal); else return Double.NaN; } else if ("px".equals(sUnitIn)) { if ("mm" .equals(sUnitOut)) return px2mm((int)nVal); else if ("inch".equals(sUnitOut)) return px2inch((int)nVal); else if ("pt" .equals(sUnitOut)) return px2pt((int)nVal); else if ("px" .equals(sUnitOut)) return nVal; else return Double.NaN; } else return Double.NaN; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.team1735; import edu.wpi.first.team1735.drive.DeadDriveController; import edu.wpi.first.team1735.drive.JoeDriveline; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Timer; /** * * @author Administrator */ public class Autonomous extends Thread { private int mode; private JoeDriveline driveline; private Joystick joystick; private Team1735 robot; public boolean autoModeBegun; public boolean teleopModeBegun; public boolean kicking; public Autonomous(JoeDriveline driveline, Joystick joystick, Team1735 robot) { this.driveline = driveline; this.autoModeBegun = false; this.teleopModeBegun = false; this.joystick = joystick; this.robot = robot; kicking = false; start(); } public void run() { boolean flag = false; boolean flag2 = false; int autodelay = 0; boolean blinkflag = false; //Whiteboard.write(1, "Team 1735"); while (!this.autoModeBegun && !this.teleopModeBegun) { if (this.joystick.getTrigger()) { if (!flag) { mode++; // Whiteboard.write(1, "1"); flag = true; if (mode > 5) { mode = 0; } } } else { flag = false; } if (this.joystick.getRawButton(2)) { if (!flag2) { autodelay++; if (autodelay > 12) { autodelay = 0; } flag2 = true; } else { flag2 = false; } } Whiteboard.write(2, "Auto Delay: " + autodelay); if (mode == 0) { if(blinkflag) { Whiteboard.write(1, "No AUTONOMOUS"); //Whiteboard.write(2, "No AUTONOMOUS"); Whiteboard.write(3, "No AUTONOMOUS"); //Whiteboard.write(4, "No AUTONOMOUS"); Whiteboard.write(5, "No AUTONOMOUS"); //Whiteboard.write(6, "No AUTONOMOUS"); blinkflag = false; } else { Whiteboard.write(1, ""); // Whiteboard.write(2, ""); Whiteboard.write(3, ""); // Whiteboard.write(4, ""); Whiteboard.write(5, ""); // Whiteboard.write(6, ""); blinkflag = true; } } else if (mode == 1) { Whiteboard.write(1, "Drive Straight"); Whiteboard.write(3, ""); Whiteboard.write(5, ""); } else if (mode == 2) { Whiteboard.write(1, "Shoot Once"); Whiteboard.write(3, ""); Whiteboard.write(5, ""); } else if (mode == 3) { Whiteboard.write(1, "Shoot Twice - Long Drive"); Whiteboard.write(3, ""); Whiteboard.write(5, ""); } else if (mode == 4) { Whiteboard.write(1, "Spin!"); Whiteboard.write(3, ""); Whiteboard.write(5, ""); } else if (mode == 5) { Whiteboard.write(1, "Drive short distance"); Whiteboard.write(3, ""); Whiteboard.write(5, ""); } Timer.delay(.05); } if(!this.teleopModeBegun) { driveline.setDriveController(new DeadDriveController()); driveline.resetGyro(); driveline.enable(); Timer.delay(autodelay); System.out.println("Passed the point"); if (mode == 1) { //shoot twice Timer.delay(1); //claw down a little robot.wrist.set(-.3); Timer.delay(.1); //Drive Straight robot.wrist.set(0); driveline.fieldOrientedAngle(.5, 0, 0);//.75 Timer.delay(2.45);//1.7 //Stop Driving, lift elevator driveline.fieldOrientedAngle(0, 0, 0); robot.elevator1.set(.5); robot.elevator2.set(.5); Timer.delay(4); //Drive straight driveline.fieldOrientedAngle(.50, 0, 0); Timer.delay(.5); driveline.fieldOrientedAngle(0,0,0); robot.wrist.set(-.3); Timer.delay(.4); robot.wrist.set(0); robot.elevator1.set(-.3); robot.elevator2.set(-.3); robot.rollersbottom.set(.5); robot.rollerstop.set(.5); Timer.delay(1.2); driveline.fieldOrientedAngle(-.5, 0, 0); robot.elevator1.set(0); robot.elevator2.set(0); Timer.delay(.8); driveline.fieldOrientedAngle(0, 0, 0); } } driveline.fieldOrientedAngle(0, 0, 0); } }
/* * Copyright 2020 Red Hat * * 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.apicurio.registry.rules.compatibility.jsonschema.diff; import org.everit.json.schema.Schema; import java.math.BigDecimal; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.function.Supplier; import static io.apicurio.registry.rules.compatibility.jsonschema.wrapper.WrapUtil.wrap; import static java.util.Objects.requireNonNull; /** * @author Jakub Senko <jsenko@redhat.com> */ public class DiffUtil { /** * added/removed * * @return true if both objects are present */ public static boolean diffAddedRemoved(DiffContext ctx, Object original, Object updated, DiffType addedType, DiffType removedType) { if (original == null && updated != null) { ctx.addDifference(addedType, original, updated); } else if (original != null && updated == null) { ctx.addDifference(removedType, original, updated); } else { return original != null; } return false; } public static <T> void diffSetChanged(DiffContext ctx, Set<T> original, Set<T> updated, DiffType addedType, DiffType removedType, DiffType changedType, DiffType addedMemberType, DiffType removedMemberType) { if (diffAddedRemoved(ctx, original, updated, addedType, removedType)) { boolean changed = false; Set<?> copyUpdated = new HashSet<>(updated); for (Object originalMember : original) { if (updated.contains(originalMember)) { // OK copyUpdated.remove(originalMember); } else { ctx.addDifference(removedMemberType, originalMember, null); changed = true; } } for (Object updatedMemberRemaining : copyUpdated) { ctx.addDifference(addedMemberType, null, updatedMemberRemaining); changed = true; } if (changed) ctx.addDifference(changedType, original, updated); } } /** * @return true if both objects are present */ public static boolean diffSubschemaAddedRemoved(DiffContext ctx, Object original, Object updated, DiffType addedType, DiffType removedType) { if (diffAddedRemoved(ctx, original, updated, addedType, removedType)) { return true; } return false; } /** * added/removed/increased/decreased * * @return true if the integers are defined and equal */ public static boolean diffInteger(DiffContext ctx, Integer original, Integer updated, DiffType addedType, DiffType removedType, DiffType increasedType, DiffType decreasedType) { if (diffAddedRemoved(ctx, original, updated, addedType, removedType)) { if (original < updated) { ctx.addDifference(increasedType, original, updated); } else if (original > updated) { ctx.addDifference(decreasedType, original, updated); } else { return true; } } return false; } /** * added/removed/increased/decreased * * @return true if the numbers are the same */ public static boolean diffNumber(DiffContext ctx, Number original, Number updated, DiffType addedType, DiffType removedType, DiffType increasedType, DiffType decreasedType) { if (diffAddedRemoved(ctx, original, updated, addedType, removedType)) { BigDecimal o = new BigDecimal(original.toString()); // Not pretty but it works:/ BigDecimal u = new BigDecimal(updated.toString()); if (o.compareTo(u) < 0) { ctx.addDifference(increasedType, original, updated); } else if (o.compareTo(u) > 0) { ctx.addDifference(decreasedType, original, updated); } else { return true; } } return false; } public static void diffNumberOriginalMultipleOfUpdated(DiffContext ctx, Number original, Number updated, DiffType multipleOfType, DiffType notMultipleOfType) { requireNonNull(original); requireNonNull(updated); BigDecimal o = new BigDecimal(original.toString()); // Not pretty but it works:/ BigDecimal u = new BigDecimal(updated.toString()); if (o.remainder(u).equals(BigDecimal.ZERO)) { ctx.addDifference(multipleOfType, original, updated); } else { ctx.addDifference(notMultipleOfType, original, updated); } } /** * */ public static void diffBooleanTransition(DiffContext ctx, Boolean original, Boolean updated, Boolean defaultValue, DiffType changeFalseToTrue, DiffType changeTrueToFalse, DiffType unchanged) { if (original == null) original = defaultValue; if (updated == null) updated = defaultValue; if (original && !updated) { ctx.addDifference(changeTrueToFalse, original, updated); } else if (!original && updated) { ctx.addDifference(changeFalseToTrue, original, updated); } else { ctx.addDifference(unchanged, original, updated); } } /** * added/removed/changed (using equals) */ public static void diffObject(DiffContext ctx, Object original, Object updated, DiffType addedType, DiffType removedType, DiffType changedType) { if (diffAddedRemoved(ctx, original, updated, addedType, removedType) && !original.equals(updated)) { ctx.addDifference(changedType, original, updated); } } /** * added/removed/changed (using equals), with a default value specified */ public static void diffObjectDefault(DiffContext ctx, Object original, Object updated, Object defaultValue, DiffType addedType, DiffType removedType, DiffType changedType) { if (Objects.equals(defaultValue, original)) original = null; if (Objects.equals(defaultValue, updated)) updated = null; if (diffAddedRemoved(ctx, original, updated, addedType, removedType) && !original.equals(updated)) { ctx.addDifference(changedType, original, updated); } } /** * added/removed/changed (using ==) * * @return true if they are equal */ public static boolean diffObjectIdentity(DiffContext ctx, Object original, Object updated, DiffType addedType, DiffType removedType, DiffType changedType) { if (diffAddedRemoved(ctx, original, updated, addedType, removedType) && original != updated) { ctx.addDifference(changedType, original, updated); return false; } return true; } public static void compareSchema(DiffContext ctx, Schema original, Schema updated, DiffType addedType, DiffType removedType, DiffType bothType, DiffType backwardNotForwardType, DiffType forwardNotBackwardType, DiffType none) { if (diffAddedRemoved(ctx, original, updated, addedType, removedType)) { DiffContext rootCtx = DiffContext.createRootContext(); new SchemaDiffVisitor(rootCtx, original) .visit(wrap(updated)); boolean backward = rootCtx.foundAllDifferencesAreCompatible(); rootCtx = DiffContext.createRootContext(); new SchemaDiffVisitor(rootCtx, updated) .visit(wrap(original)); boolean forward = rootCtx.foundAllDifferencesAreCompatible(); if (backward && forward) { ctx.addDifference(bothType, original, updated); } if (backward && !forward) { ctx.addDifference(backwardNotForwardType, original, updated); } if (!backward && forward) { ctx.addDifference(forwardNotBackwardType, original, updated); } if (!backward && !forward) { ctx.addDifference(none, original, updated); } } } /** * Use getter and return null if there is an exception. */ public static <T> T getExceptionally(DiffContext ctx, Supplier<T> getter) { try { return getter.get(); } catch (Exception ex) { ctx.log("Caught exception when getting exceptionally: " + ex + ". Returning null."); return null; } } }
/** * Copyright (C) 2015 Michael Schnell. All rights reserved. * http://www.fuin.org/ * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) any * later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see http://www.gnu.org/licenses/. */ package org.fuin.cqrs4j.example.shared; import javax.json.bind.annotation.JsonbProperty; import javax.validation.constraints.NotNull; import org.fuin.cqrs4j.AbstractAggregateCommand; import org.fuin.ddd4j.ddd.DomainEventExpectedEntityIdPath; import org.fuin.ddd4j.ddd.EventType; import org.fuin.esc.spi.SerializedDataType; import org.fuin.objects4j.common.Contract; import org.fuin.objects4j.common.Immutable; /** * A new person should be created in the system. */ @Immutable @DomainEventExpectedEntityIdPath(PersonId.class) public final class CreatePersonCommand extends AbstractAggregateCommand<PersonId, PersonId> { private static final long serialVersionUID = 1000L; /** Never changing unique event type name. */ public static final EventType TYPE = new EventType("CreatePersonCommand"); /** Unique name used for marshalling/unmarshalling the event. */ public static final SerializedDataType SER_TYPE = new SerializedDataType(CreatePersonCommand.TYPE.asBaseType()); @NotNull @JsonbProperty("name") private PersonName name; /** * Protected default constructor for deserialization. */ protected CreatePersonCommand() { super(); } /** * A new person was created in the system. * * @param id * Identifies uniquely a person. * @param name * Name of a person. */ public CreatePersonCommand(@NotNull final PersonId id, @NotNull final PersonName name) { super(id, null); Contract.requireArgNotNull("name", name); this.name = name; } @Override public final EventType getEventType() { return CreatePersonCommand.TYPE; } /** * Returns: Name of a person. * * @return Current value. */ @NotNull public final PersonName getName() { return name; } @Override public final String toString() { return "Create person '" + name + "' with identifier '" + getAggregateRootId() + "'"; } }
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.search.aggregations.bucket.histogram; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.search.ScoreMode; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.CollectionUtil; import org.opensearch.common.Nullable; import org.opensearch.common.Rounding; import org.opensearch.common.lease.Releasables; import org.opensearch.index.fielddata.SortedBinaryDocValues; import org.opensearch.index.mapper.RangeFieldMapper; import org.opensearch.index.mapper.RangeType; import org.opensearch.search.DocValueFormat; import org.opensearch.search.aggregations.Aggregator; import org.opensearch.search.aggregations.AggregatorFactories; import org.opensearch.search.aggregations.BucketOrder; import org.opensearch.search.aggregations.CardinalityUpperBound; import org.opensearch.search.aggregations.InternalAggregation; import org.opensearch.search.aggregations.LeafBucketCollector; import org.opensearch.search.aggregations.LeafBucketCollectorBase; import org.opensearch.search.aggregations.bucket.BucketsAggregator; import org.opensearch.search.aggregations.bucket.terms.LongKeyedBucketOrds; import org.opensearch.search.aggregations.support.ValuesSource; import org.opensearch.search.aggregations.support.ValuesSourceConfig; import org.opensearch.search.internal.SearchContext; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import static java.lang.Long.max; import static java.lang.Long.min; /** * An aggregator for date values. Every date is rounded down using a configured * {@link Rounding}. * * @see Rounding * * @opensearch.internal */ class DateRangeHistogramAggregator extends BucketsAggregator { private final ValuesSource.Range valuesSource; private final DocValueFormat formatter; private final Rounding rounding; /** * The rounding prepared for rewriting the data in the shard. */ private final Rounding.Prepared preparedRounding; private final BucketOrder order; private final boolean keyed; private final long minDocCount; private final LongBounds extendedBounds; private final LongBounds hardBounds; private final LongKeyedBucketOrds bucketOrds; DateRangeHistogramAggregator( String name, AggregatorFactories factories, Rounding rounding, Rounding.Prepared preparedRounding, BucketOrder order, boolean keyed, long minDocCount, @Nullable LongBounds extendedBounds, @Nullable LongBounds hardBounds, ValuesSourceConfig valuesSourceConfig, SearchContext aggregationContext, Aggregator parent, CardinalityUpperBound cardinality, Map<String, Object> metadata ) throws IOException { super(name, factories, aggregationContext, parent, CardinalityUpperBound.MANY, metadata); this.rounding = rounding; this.preparedRounding = preparedRounding; this.order = order; order.validate(this); this.keyed = keyed; this.minDocCount = minDocCount; this.extendedBounds = extendedBounds; this.hardBounds = hardBounds; // TODO: Stop using null here this.valuesSource = valuesSourceConfig.hasValues() ? (ValuesSource.Range) valuesSourceConfig.getValuesSource() : null; this.formatter = valuesSourceConfig.format(); if (this.valuesSource.rangeType() != RangeType.DATE) { throw new IllegalArgumentException( "Expected date range type but found range type [" + this.valuesSource.rangeType().name + "]" ); } bucketOrds = LongKeyedBucketOrds.build(context.bigArrays(), cardinality); } @Override public ScoreMode scoreMode() { if (valuesSource != null && valuesSource.needsScores()) { return ScoreMode.COMPLETE; } return super.scoreMode(); } @Override public LeafBucketCollector getLeafCollector(LeafReaderContext ctx, LeafBucketCollector sub) throws IOException { if (valuesSource == null) { return LeafBucketCollector.NO_OP_COLLECTOR; } SortedBinaryDocValues values = valuesSource.bytesValues(ctx); RangeType rangeType = valuesSource.rangeType(); return new LeafBucketCollectorBase(sub, values) { @Override public void collect(int doc, long owningBucketOrd) throws IOException { if (values.advanceExact(doc)) { // Is it possible for valuesCount to be > 1 here? Multiple ranges are encoded into the same BytesRef in the binary doc // values, so it isn't clear what we'd be iterating over. int valuesCount = values.docValueCount(); assert valuesCount == 1 : "Value count for ranges should always be 1"; long previousKey = Long.MIN_VALUE; for (int i = 0; i < valuesCount; i++) { BytesRef encodedRanges = values.nextValue(); List<RangeFieldMapper.Range> ranges = rangeType.decodeRanges(encodedRanges); long previousFrom = Long.MIN_VALUE; for (RangeFieldMapper.Range range : ranges) { Long from = (Long) range.getFrom(); // The encoding should ensure that this assert is always true. assert from >= previousFrom : "Start of range not >= previous start"; final Long to = (Long) range.getTo(); final long effectiveFrom = (hardBounds != null && hardBounds.getMin() != null) ? max(from, hardBounds.getMin()) : from; final long effectiveTo = (hardBounds != null && hardBounds.getMax() != null) ? min(to, hardBounds.getMax()) : to; final long startKey = preparedRounding.round(effectiveFrom); final long endKey = preparedRounding.round(effectiveTo); for (long key = max(startKey, previousKey); key <= endKey; key = preparedRounding.nextRoundingValue(key)) { if (key == previousKey) { continue; } // Bucket collection identical to NumericHistogramAggregator, could be refactored long bucketOrd = bucketOrds.add(owningBucketOrd, key); if (bucketOrd < 0) { // already seen bucketOrd = -1 - bucketOrd; collectExistingBucket(sub, doc, bucketOrd); } else { collectBucket(sub, doc, bucketOrd); } } if (endKey > previousKey) { previousKey = endKey; } } } } } }; } @Override public InternalAggregation[] buildAggregations(long[] owningBucketOrds) throws IOException { return buildAggregationsForVariableBuckets( owningBucketOrds, bucketOrds, (bucketValue, docCount, subAggregationResults) -> new InternalDateHistogram.Bucket( bucketValue, docCount, keyed, formatter, subAggregationResults ), (owningBucketOrd, buckets) -> { // the contract of the histogram aggregation is that shards must return buckets ordered by key in ascending order CollectionUtil.introSort(buckets, BucketOrder.key(true).comparator()); // value source will be null for unmapped fields // Important: use `rounding` here, not `shardRounding` InternalDateHistogram.EmptyBucketInfo emptyBucketInfo = minDocCount == 0 ? new InternalDateHistogram.EmptyBucketInfo(rounding.withoutOffset(), buildEmptySubAggregations(), extendedBounds) : null; return new InternalDateHistogram( name, buckets, order, minDocCount, rounding.offset(), emptyBucketInfo, formatter, keyed, metadata() ); } ); } @Override public InternalAggregation buildEmptyAggregation() { InternalDateHistogram.EmptyBucketInfo emptyBucketInfo = minDocCount == 0 ? new InternalDateHistogram.EmptyBucketInfo(rounding, buildEmptySubAggregations(), extendedBounds) : null; return new InternalDateHistogram( name, Collections.emptyList(), order, minDocCount, rounding.offset(), emptyBucketInfo, formatter, keyed, metadata() ); } @Override public void doClose() { Releasables.close(bucketOrds); } @Override public void collectDebugInfo(BiConsumer<String, Object> add) { add.accept("total_buckets", bucketOrds.size()); } }
/* * Copyright 2011-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 com.amazonaws.services.gamelift.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * Represents the input for a request action. * </p> */ public class UpdateGameSessionRequest extends AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * Unique identifier for a game session. Specify the game session you want * to update. * </p> */ private String gameSessionId; /** * <p> * Maximum number of players that can be simultaneously connected to the * game session. * </p> */ private Integer maximumPlayerSessionCount; /** * <p> * Descriptive label associated with a game session. Session names do not * need to be unique. * </p> */ private String name; /** * <p> * Policy determining whether or not the game session accepts new players. * </p> */ private String playerSessionCreationPolicy; /** * <p> * Game session protection policy to apply to this game session only. * </p> * <ul> * <li><b>NoProtection</b> – The game session can be terminated during a * scale-down event.</li> * <li><b>FullProtection</b> – If the game session is in an * <code>ACTIVE</code> status, it cannot be terminated during a scale-down * event.</li> * </ul> */ private String protectionPolicy; /** * <p> * Unique identifier for a game session. Specify the game session you want * to update. * </p> * * @param gameSessionId * Unique identifier for a game session. Specify the game session you * want to update. */ public void setGameSessionId(String gameSessionId) { this.gameSessionId = gameSessionId; } /** * <p> * Unique identifier for a game session. Specify the game session you want * to update. * </p> * * @return Unique identifier for a game session. Specify the game session * you want to update. */ public String getGameSessionId() { return this.gameSessionId; } /** * <p> * Unique identifier for a game session. Specify the game session you want * to update. * </p> * * @param gameSessionId * Unique identifier for a game session. Specify the game session you * want to update. * @return Returns a reference to this object so that method calls can be * chained together. */ public UpdateGameSessionRequest withGameSessionId(String gameSessionId) { setGameSessionId(gameSessionId); return this; } /** * <p> * Maximum number of players that can be simultaneously connected to the * game session. * </p> * * @param maximumPlayerSessionCount * Maximum number of players that can be simultaneously connected to * the game session. */ public void setMaximumPlayerSessionCount(Integer maximumPlayerSessionCount) { this.maximumPlayerSessionCount = maximumPlayerSessionCount; } /** * <p> * Maximum number of players that can be simultaneously connected to the * game session. * </p> * * @return Maximum number of players that can be simultaneously connected to * the game session. */ public Integer getMaximumPlayerSessionCount() { return this.maximumPlayerSessionCount; } /** * <p> * Maximum number of players that can be simultaneously connected to the * game session. * </p> * * @param maximumPlayerSessionCount * Maximum number of players that can be simultaneously connected to * the game session. * @return Returns a reference to this object so that method calls can be * chained together. */ public UpdateGameSessionRequest withMaximumPlayerSessionCount( Integer maximumPlayerSessionCount) { setMaximumPlayerSessionCount(maximumPlayerSessionCount); return this; } /** * <p> * Descriptive label associated with a game session. Session names do not * need to be unique. * </p> * * @param name * Descriptive label associated with a game session. Session names do * not need to be unique. */ public void setName(String name) { this.name = name; } /** * <p> * Descriptive label associated with a game session. Session names do not * need to be unique. * </p> * * @return Descriptive label associated with a game session. Session names * do not need to be unique. */ public String getName() { return this.name; } /** * <p> * Descriptive label associated with a game session. Session names do not * need to be unique. * </p> * * @param name * Descriptive label associated with a game session. Session names do * not need to be unique. * @return Returns a reference to this object so that method calls can be * chained together. */ public UpdateGameSessionRequest withName(String name) { setName(name); return this; } /** * <p> * Policy determining whether or not the game session accepts new players. * </p> * * @param playerSessionCreationPolicy * Policy determining whether or not the game session accepts new * players. * @see PlayerSessionCreationPolicy */ public void setPlayerSessionCreationPolicy( String playerSessionCreationPolicy) { this.playerSessionCreationPolicy = playerSessionCreationPolicy; } /** * <p> * Policy determining whether or not the game session accepts new players. * </p> * * @return Policy determining whether or not the game session accepts new * players. * @see PlayerSessionCreationPolicy */ public String getPlayerSessionCreationPolicy() { return this.playerSessionCreationPolicy; } /** * <p> * Policy determining whether or not the game session accepts new players. * </p> * * @param playerSessionCreationPolicy * Policy determining whether or not the game session accepts new * players. * @return Returns a reference to this object so that method calls can be * chained together. * @see PlayerSessionCreationPolicy */ public UpdateGameSessionRequest withPlayerSessionCreationPolicy( String playerSessionCreationPolicy) { setPlayerSessionCreationPolicy(playerSessionCreationPolicy); return this; } /** * <p> * Policy determining whether or not the game session accepts new players. * </p> * * @param playerSessionCreationPolicy * Policy determining whether or not the game session accepts new * players. * @see PlayerSessionCreationPolicy */ public void setPlayerSessionCreationPolicy( PlayerSessionCreationPolicy playerSessionCreationPolicy) { this.playerSessionCreationPolicy = playerSessionCreationPolicy .toString(); } /** * <p> * Policy determining whether or not the game session accepts new players. * </p> * * @param playerSessionCreationPolicy * Policy determining whether or not the game session accepts new * players. * @return Returns a reference to this object so that method calls can be * chained together. * @see PlayerSessionCreationPolicy */ public UpdateGameSessionRequest withPlayerSessionCreationPolicy( PlayerSessionCreationPolicy playerSessionCreationPolicy) { setPlayerSessionCreationPolicy(playerSessionCreationPolicy); return this; } /** * <p> * Game session protection policy to apply to this game session only. * </p> * <ul> * <li><b>NoProtection</b> – The game session can be terminated during a * scale-down event.</li> * <li><b>FullProtection</b> – If the game session is in an * <code>ACTIVE</code> status, it cannot be terminated during a scale-down * event.</li> * </ul> * * @param protectionPolicy * Game session protection policy to apply to this game session * only.</p> * <ul> * <li><b>NoProtection</b> – The game session can be terminated * during a scale-down event.</li> * <li><b>FullProtection</b> – If the game session is in an * <code>ACTIVE</code> status, it cannot be terminated during a * scale-down event.</li> * @see ProtectionPolicy */ public void setProtectionPolicy(String protectionPolicy) { this.protectionPolicy = protectionPolicy; } /** * <p> * Game session protection policy to apply to this game session only. * </p> * <ul> * <li><b>NoProtection</b> – The game session can be terminated during a * scale-down event.</li> * <li><b>FullProtection</b> – If the game session is in an * <code>ACTIVE</code> status, it cannot be terminated during a scale-down * event.</li> * </ul> * * @return Game session protection policy to apply to this game session * only.</p> * <ul> * <li><b>NoProtection</b> – The game session can be terminated * during a scale-down event.</li> * <li><b>FullProtection</b> – If the game session is in an * <code>ACTIVE</code> status, it cannot be terminated during a * scale-down event.</li> * @see ProtectionPolicy */ public String getProtectionPolicy() { return this.protectionPolicy; } /** * <p> * Game session protection policy to apply to this game session only. * </p> * <ul> * <li><b>NoProtection</b> – The game session can be terminated during a * scale-down event.</li> * <li><b>FullProtection</b> – If the game session is in an * <code>ACTIVE</code> status, it cannot be terminated during a scale-down * event.</li> * </ul> * * @param protectionPolicy * Game session protection policy to apply to this game session * only.</p> * <ul> * <li><b>NoProtection</b> – The game session can be terminated * during a scale-down event.</li> * <li><b>FullProtection</b> – If the game session is in an * <code>ACTIVE</code> status, it cannot be terminated during a * scale-down event.</li> * @return Returns a reference to this object so that method calls can be * chained together. * @see ProtectionPolicy */ public UpdateGameSessionRequest withProtectionPolicy(String protectionPolicy) { setProtectionPolicy(protectionPolicy); return this; } /** * <p> * Game session protection policy to apply to this game session only. * </p> * <ul> * <li><b>NoProtection</b> – The game session can be terminated during a * scale-down event.</li> * <li><b>FullProtection</b> – If the game session is in an * <code>ACTIVE</code> status, it cannot be terminated during a scale-down * event.</li> * </ul> * * @param protectionPolicy * Game session protection policy to apply to this game session * only.</p> * <ul> * <li><b>NoProtection</b> – The game session can be terminated * during a scale-down event.</li> * <li><b>FullProtection</b> – If the game session is in an * <code>ACTIVE</code> status, it cannot be terminated during a * scale-down event.</li> * @see ProtectionPolicy */ public void setProtectionPolicy(ProtectionPolicy protectionPolicy) { this.protectionPolicy = protectionPolicy.toString(); } /** * <p> * Game session protection policy to apply to this game session only. * </p> * <ul> * <li><b>NoProtection</b> – The game session can be terminated during a * scale-down event.</li> * <li><b>FullProtection</b> – If the game session is in an * <code>ACTIVE</code> status, it cannot be terminated during a scale-down * event.</li> * </ul> * * @param protectionPolicy * Game session protection policy to apply to this game session * only.</p> * <ul> * <li><b>NoProtection</b> – The game session can be terminated * during a scale-down event.</li> * <li><b>FullProtection</b> – If the game session is in an * <code>ACTIVE</code> status, it cannot be terminated during a * scale-down event.</li> * @return Returns a reference to this object so that method calls can be * chained together. * @see ProtectionPolicy */ public UpdateGameSessionRequest withProtectionPolicy( ProtectionPolicy protectionPolicy) { setProtectionPolicy(protectionPolicy); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getGameSessionId() != null) sb.append("GameSessionId: " + getGameSessionId() + ","); if (getMaximumPlayerSessionCount() != null) sb.append("MaximumPlayerSessionCount: " + getMaximumPlayerSessionCount() + ","); if (getName() != null) sb.append("Name: " + getName() + ","); if (getPlayerSessionCreationPolicy() != null) sb.append("PlayerSessionCreationPolicy: " + getPlayerSessionCreationPolicy() + ","); if (getProtectionPolicy() != null) sb.append("ProtectionPolicy: " + getProtectionPolicy()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateGameSessionRequest == false) return false; UpdateGameSessionRequest other = (UpdateGameSessionRequest) obj; if (other.getGameSessionId() == null ^ this.getGameSessionId() == null) return false; if (other.getGameSessionId() != null && other.getGameSessionId().equals(this.getGameSessionId()) == false) return false; if (other.getMaximumPlayerSessionCount() == null ^ this.getMaximumPlayerSessionCount() == null) return false; if (other.getMaximumPlayerSessionCount() != null && other.getMaximumPlayerSessionCount().equals( this.getMaximumPlayerSessionCount()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getPlayerSessionCreationPolicy() == null ^ this.getPlayerSessionCreationPolicy() == null) return false; if (other.getPlayerSessionCreationPolicy() != null && other.getPlayerSessionCreationPolicy().equals( this.getPlayerSessionCreationPolicy()) == false) return false; if (other.getProtectionPolicy() == null ^ this.getProtectionPolicy() == null) return false; if (other.getProtectionPolicy() != null && other.getProtectionPolicy().equals( this.getProtectionPolicy()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getGameSessionId() == null) ? 0 : getGameSessionId() .hashCode()); hashCode = prime * hashCode + ((getMaximumPlayerSessionCount() == null) ? 0 : getMaximumPlayerSessionCount().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getPlayerSessionCreationPolicy() == null) ? 0 : getPlayerSessionCreationPolicy().hashCode()); hashCode = prime * hashCode + ((getProtectionPolicy() == null) ? 0 : getProtectionPolicy() .hashCode()); return hashCode; } @Override public UpdateGameSessionRequest clone() { return (UpdateGameSessionRequest) super.clone(); } }
package com.jfrog.ide.idea.inspections; import com.goide.vgo.mod.psi.VgoModuleSpec; /** * Created by Bar Belity on 23/02/2020. */ public class GoInspectionTest extends InspectionsTest { private static final String PACKAGE_DESCRIPTOR = "go.mod"; private final Object[][] DEPENDENCIES = { // offset, groupId, artifactId {54, "", "github.com/jfrog/gocmd"}, {89, "", "github.com/jfrog/gofrog"}, {124, "", "github.com/jfrog/gogopowerrangers"} }; private final int[] NON_DEPENDENCIES_POSITIONS = {176, 202}; @SuppressWarnings("MethodDoesntCallSuperMethod") @Override public void setUp() throws Exception { super.setUp(new GoInspection(), PACKAGE_DESCRIPTOR, VgoModuleSpec.class); } public void testDependencies() { isDependencyTest(DEPENDENCIES); } public void testNonDependencies() { isNonDependencyTest(NON_DEPENDENCIES_POSITIONS); } public void testCreateGeneralInfo() { createGeneralInfoTest(DEPENDENCIES); } }
package br.rj.senac.biblisoft.view; import java.awt.ComponentOrientation; import java.awt.Dimension; import java.awt.Font; import java.awt.Rectangle; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import br.rj.senac.biblisoft.control.EditoraController; import br.rj.senac.biblisoft.exception.BusinessException; import br.rj.senac.biblisoft.exception.DAOException; import br.rj.senac.biblisoft.exception.DatabaseException; import br.rj.senac.biblisoft.model.Editora; import br.rj.senac.biblisoft.model.conexao.Conexao; import br.rj.senac.biblisoft.model.table.EditoraTableModel; public class EditoraView extends EntityModelView { private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JButton insertBut = null; private JButton deleteBut = null; private JTextField nomeField = null; private JTextField idField = null; private JButton updateBut = null; private JButton selectBut = null; private JScrollPane jScrollPane = null; private JTable jTable1 = null; // @jve:decl-index=0:visual-constraint="-211,288" private EditoraTableModel editoraModel = new EditoraTableModel( EditoraTableModel.dados, EditoraTableModel.colunas); private JLabel nomeLab = null; private JLabel idLab = null; private EditoraController editoraController = new EditoraController(); // @jve:decl-index=0: private JButton getInsertBut() { if (insertBut == null) { insertBut = new JButton(); insertBut.setBounds(new Rectangle(258, 13, 116, 24)); insertBut.setFont(new Font("Comic Sans MS", Font.BOLD, 12)); insertBut.setText("CADASTRAR"); insertBut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { Editora editora = new Editora(); editora.setNome(getNomeField().getText()); try { editoraController.inserirEditora(editora); } catch (BusinessException e1) { e1.printStackTrace(); } catch (DatabaseException e1) { e1.printStackTrace(); } Integer id = null; try { id = editoraController.getId(editora); } catch (DAOException e1) { e1.printStackTrace(); } String[] linha = new String[] { "" + id, editora.getNome() }; editoraModel.addRow(linha); Conexao.closeConn(); } }); } return insertBut; } private JButton getDeleteBut() { if (deleteBut == null) { deleteBut = new JButton(); deleteBut.setBounds(new Rectangle(258, 159, 116, 24)); deleteBut.setText("DELETAR"); deleteBut.setFont(new Font("Comic Sans MS", Font.BOLD, 12)); deleteBut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { Editora editora = new Editora(); int id = -99999; int x; boolean oi; for (x = 0; x < jTable1.getRowCount(); x++) { oi = jTable1.isRowSelected(x); if (oi == true) { String y = (String) jTable1.getValueAt(x, 0); id = Integer.parseInt(y); editora.setId(id); try { editoraController.excluirEditora(editora); } catch (BusinessException e1) { e1.printStackTrace(); } catch (DatabaseException e1) { e1.printStackTrace(); } editoraModel.removeRow(x); } } } }); } return deleteBut; } public JTextField getNomeField() { if (nomeField == null) { nomeField = new JTextField(); nomeField.setBounds(new Rectangle(60, 13, 175, 16)); nomeField.setFont(new Font("Comic Sans MS", Font.PLAIN, 11)); } return nomeField; } public JTextField getIdField() { if (idField == null) { idField = new JTextField(); idField.setBounds(new Rectangle(60, 34, 72, 16)); idField.setEditable(false); idField.setFont(new Font("Comic Sans MS", Font.PLAIN, 11)); } return idField; } private JButton getUpdateBut() { if (updateBut == null) { updateBut = new JButton(); updateBut.setBounds(new Rectangle(258, 52, 116, 24)); updateBut.setText("ALTERAR"); updateBut.setFont(new Font("Comic Sans MS", Font.BOLD, 12)); updateBut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { Editora editora = new Editora(); int id = Integer.parseInt(getIdField().getText()); editora.setId(id); editora.setNome(getNomeField().getText()); try { editoraController.alterarEditora(editora); } catch (BusinessException e1) { e1.printStackTrace(); } catch (DatabaseException e1) { e1.printStackTrace(); } int z = Integer.parseInt(getIdField().getText()); editora.setId(z); String[] linha = new String[] { "" + editora.getId(), editora.getNome() }; editoraModel.addRow(linha); int idd = -99999; int x; boolean oi; for (x = 0; x < jTable1.getRowCount(); x++) { oi = jTable1.isRowSelected(x); if (oi == true) { String y = (String) jTable1.getValueAt(x, 0); idd = Integer.parseInt(y); editora.setId(idd); editoraModel.removeRow(x); } } } }); } return updateBut; } private EditoraView getThis() { return this; } private JButton getSelectBut() { if (selectBut == null) { selectBut = new JButton(); selectBut.setBounds(new Rectangle(258, 123, 116, 24)); selectBut.setText("SELECIONAR"); selectBut.setFont(new Font("Comic Sans MS", Font.BOLD, 12)); selectBut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { Editora editora = new Editora(); int id = -99999; int x; boolean oi; for (x = 0; x < jTable1.getRowCount(); x++) { oi = jTable1.isRowSelected(x); if (oi == true) { String y = (String) jTable1.getValueAt(x, 0); id = Integer.parseInt(y); editora.setId(id); try { editoraController.select(editora, getThis()); } catch (BusinessException e1) { e1.printStackTrace(); } catch (DatabaseException e1) { e1.printStackTrace(); } } } } }); } return selectBut; } private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(25, 56, 216, 261)); jScrollPane.setViewportView(getJTable1()); } return jScrollPane; } private JTable getJTable1() { if (jTable1 == null) { jTable1 = new JTable(editoraModel); jTable1.setName("EditorasTable"); jTable1.setColumnSelectionAllowed(false); jTable1.setRowSelectionAllowed(true); jTable1.setShowGrid(true); jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); jTable1.setComponentOrientation(ComponentOrientation.UNKNOWN); jTable1.setSize(new Dimension(213, 8)); jTable1.setCellSelectionEnabled(true); jTable1.setFont(new Font("Comic Sans MS", Font.PLAIN, 11)); } return jTable1; } public void select() { boolean oi; for (int x = 0; x < jTable1.getRowCount(); x++) { oi = jTable1.isRowSelected(x); if (oi == true) { System.out.println(jTable1.getValueAt(x, 0)); } } } public EditoraView() { super(); initialize(); } private void initialize() { this.setSize(390, 366); this.setContentPane(getJContentPane()); this.setTitle("EditoraView"); this.setVisible(true); this.setFont(new Font("Comic Sans MS", Font.BOLD, 12)); } private JPanel getJContentPane() { if (jContentPane == null) { idLab = new JLabel(); idLab.setBounds(new Rectangle(31, 34, 21, 16)); idLab.setText("ID:"); idLab.setFont(new Font("Comic Sans MS", Font.BOLD, 12)); nomeLab = new JLabel(); nomeLab.setBounds(new Rectangle(8, 13, 44, 16)); nomeLab.setText("NOME:"); nomeLab.setFont(new Font("Comic Sans MS", Font.BOLD, 12)); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(getInsertBut(), null); jContentPane.add(getDeleteBut(), null); jContentPane.add(getNomeField(), null); jContentPane.add(getIdField(), null); jContentPane.add(getUpdateBut(), null); jContentPane.add(getSelectBut(), null); jContentPane.add(getJScrollPane(), null); jContentPane.add(nomeLab, null); jContentPane.add(idLab, null); } return jContentPane; } }
package com.pricemonitor.configserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; @SpringBootApplication @EnableConfigServer public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } }
/// usr/bin/env jbang "$0" "$@" ; exit $? //DEPS org.assertj:assertj-core:3.21.0 //DEPS org.apache.commons:commons-math3:3.6.1 package edu.jab.math; import java.math.BigDecimal; import java.util.function.Predicate; import java.util.stream.Stream; import org.apache.commons.math3.primes.Primes; public class Problem20211226 { public static void main(String[] args) { Predicate<Integer> isPrime = number -> Primes.isPrime(number); Predicate<Integer> isOdd = number -> (number % 2 == 0) ? false : true; var result = Stream .iterate(1, i -> i + 1) // Infinite Stream .skip(1) // 1 is not a prime number .filter(isPrime) .filter(isOdd) .limit(4) .peek(System.out::println) .map(BigDecimal::valueOf) .reduce(BigDecimal.ZERO, BigDecimal::add); // Sum System.out.print("Result: " + result); } }
package cn.exrick.manager.controller; import cn.exrick.common.constant.CountConstant; import cn.exrick.common.pojo.Result; import cn.exrick.common.utils.ResultUtil; import cn.exrick.manager.dto.ChartData; import cn.exrick.manager.dto.OrderChartData; import cn.exrick.manager.service.CountService; import cn.hutool.core.date.DateUnit; import cn.hutool.core.date.DateUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author Exrickx */ @RestController @Api(description = "统计") public class CountController { @Autowired private CountService countService; @RequestMapping(value = "/count/order",method = RequestMethod.GET) @ApiOperation(value = "通过panelId获得板块内容列表") public Result<Object> countOrder(@RequestParam int type, @RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime, @RequestParam(required = false) int year){ ChartData data = new ChartData(); Date startDate = null, endDate = null; if(type == CountConstant.CUSTOM_DATE){ startDate = DateUtil.beginOfDay(DateUtil.parse(startTime)); endDate = DateUtil.endOfDay(DateUtil.parse(endTime)); long betweenDay = DateUtil.between(startDate, endDate, DateUnit.DAY); if(betweenDay>31){ return new ResultUtil<Object>().setErrorMsg("所选日期范围过长,最多不能超过31天"); } } List<OrderChartData> list = countService.getOrderCountData(type, startDate, endDate, year); List<Object> xDatas = new ArrayList<>(); List<Object> yDatas = new ArrayList<>(); BigDecimal countAll = new BigDecimal("0"); for(OrderChartData orderData : list){ if(type==CountConstant.CUSTOM_YEAR){ xDatas.add(DateUtil.format(orderData.getTime(),"yyyy-MM")); }else{ xDatas.add(DateUtil.formatDate(orderData.getTime())); } yDatas.add(orderData.getMoney()); countAll=countAll.add(orderData.getMoney()); } data.setxDatas(xDatas); data.setyDatas(yDatas); data.setCountAll(countAll); return new ResultUtil<Object>().setData(data); } }
/* * 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.catalina.tribes.demos; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import org.apache.catalina.tribes.Channel; import org.apache.catalina.tribes.Member; import org.apache.catalina.tribes.group.GroupChannel; import org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor; import org.apache.catalina.tribes.group.interceptors.NonBlockingCoordinator; import org.apache.catalina.tribes.group.interceptors.TcpFailureDetector; import org.apache.catalina.tribes.transport.ReceiverBase; import org.apache.catalina.tribes.util.Arrays; public class CoordinationDemo { static int CHANNEL_COUNT = 5; static int SCREEN_WIDTH = 120; static long SLEEP_TIME = 10; static int CLEAR_SCREEN = 30; static boolean MULTI_THREAD = false; static boolean[] VIEW_EVENTS = new boolean[255]; StringBuilder statusLine = new StringBuilder(); Status[] status = null; BufferedReader reader = null; /** * Construct and show the application. */ public CoordinationDemo() { // Default constructor } public void init() { reader = new BufferedReader(new InputStreamReader(System.in)); status = new Status[CHANNEL_COUNT]; } public void clearScreen() { StringBuilder buf = new StringBuilder(700); for (int i=0; i<CLEAR_SCREEN; i++ ) buf.append("\n"); System.out.println(buf); } public void printMenuOptions() { System.out.println("Commands:"); System.out.println("\tstart [member id]"); System.out.println("\tstop [member id]"); System.out.println("\tprint (refresh)"); System.out.println("\tquit"); System.out.print("Enter command:"); } public synchronized void printScreen() { clearScreen(); System.out.println(" ###."+getHeader()); for ( int i=0; i<status.length; i++ ) { System.out.print(leftfill(String.valueOf(i+1)+".",5," ")); if ( status[i] != null ) System.out.print(status[i].getStatusLine()); } System.out.println("\n\n"); System.out.println("Overall status:"+statusLine); printMenuOptions(); } public String getHeader() { //member - 30 //running- 10 //coord - 30 //view-id - 24 //view count - 8 StringBuilder buf = new StringBuilder(); buf.append(leftfill("Member",30," ")); buf.append(leftfill("Running",10," ")); buf.append(leftfill("Coord",30," ")); buf.append(leftfill("View-id(short)",24," ")); buf.append(leftfill("Count",8," ")); buf.append("\n"); buf.append(rightfill("==="+new java.sql.Timestamp(System.currentTimeMillis()).toString(),SCREEN_WIDTH,"=")); buf.append("\n"); return buf.toString(); } public String[] tokenize(String line) { StringTokenizer tz = new StringTokenizer(line," "); String[] result = new String[tz.countTokens()]; for (int i=0; i<result.length; i++ ) result[i] = tz.nextToken(); return result; } public void waitForInput() throws IOException { for ( int i=0; i<status.length; i++ ) status[i] = new Status(this); printScreen(); String l = reader.readLine(); String[] args; if (l == null) { args = new String[] {}; } else { args = tokenize(l); } while ( args.length >= 1 && (!"quit".equalsIgnoreCase(args[0]))) { if ("start".equalsIgnoreCase(args[0])) { cmdStart(args); } else if ("stop".equalsIgnoreCase(args[0])) { cmdStop(args); } printScreen(); l = reader.readLine(); if (l != null) { args = tokenize(l); } } for (Status value : status) value.stop(); } private void cmdStop(String[] args) { if ( args.length == 1 ) { setSystemStatus("System shutting down..."); Thread[] t = new Thread[CHANNEL_COUNT]; for (int i = 0; i < status.length; i++) { final int j = i; t[j] = new Thread() { @Override public void run() { status[j].stop(); } }; } for (int i = 0; i < status.length; i++) if (MULTI_THREAD ) t[i].start(); else t[i].run(); setSystemStatus("System stopped."); } else { int index = -1; try { index = Integer.parseInt(args[1])-1;}catch ( Exception x ) {setSystemStatus("Invalid index:"+args[1]);} if ( index >= 0 ) { setSystemStatus("Stopping member:"+(index+1)); status[index].stop(); setSystemStatus("Member stopped:"+(index+1)); } } } private void cmdStart(String[] args) { if ( args.length == 1 ) { setSystemStatus("System starting up..."); Thread[] t = new Thread[CHANNEL_COUNT]; for (int i = 0; i < status.length; i++) { final int j = i; t[j] = new Thread() { @Override public void run() { status[j].start(); } }; } for (int i = 0; i < status.length; i++) if (MULTI_THREAD ) t[i].start(); else t[i].run(); setSystemStatus("System started."); } else { int index = -1; try { index = Integer.parseInt(args[1])-1;}catch ( Exception x ) {setSystemStatus("Invalid index:"+args[1]);} if ( index >= 0 ) { setSystemStatus("Starting member:"+(index+1)); status[index].start(); setSystemStatus("Member started:"+(index+1)); } } } public void setSystemStatus(String status) { statusLine.delete(0,statusLine.length()); statusLine.append(status); } public static void setEvents(String events) { java.util.Arrays.fill(VIEW_EVENTS,false); StringTokenizer t = new StringTokenizer(events,","); while (t.hasMoreTokens() ) { int idx = Integer.parseInt(t.nextToken()); VIEW_EVENTS[idx] = true; } } public static void run(String[] args,CoordinationDemo demo) throws Exception { usage(); java.util.Arrays.fill(VIEW_EVENTS,true); for (int i=0; i<args.length; i++ ) { if ( "-c".equals(args[i]) ) CHANNEL_COUNT = Integer.parseInt(args[++i]); else if ( "-t".equals(args[i]) ) MULTI_THREAD = Boolean.parseBoolean(args[++i]); else if ( "-s".equals(args[i]) ) SLEEP_TIME = Long.parseLong(args[++i]); else if ( "-sc".equals(args[i]) ) CLEAR_SCREEN = Integer.parseInt(args[++i]); else if ( "-p".equals(args[i]) ) setEvents(args[++i]); else if ( "-h".equals(args[i]) ) System.exit(0); } demo.init(); demo.waitForInput(); } private static void usage() { System.out.println("Usage:"); System.out.println("\tjava org.apache.catalina.tribes.demos.CoordinationDemo -c channel-count(int) -t multi-thread(true|false) -s sleep-time(ms) -sc clear-screen(int) -p view_events_csv(1,2,5,7)"); System.out.println("Example:"); System.out.println("\tjava o.a.c.t.d.CoordinationDemo -> starts demo single threaded start/stop with 5 channels"); System.out.println("\tjava o.a.c.t.d.CoordinationDemo -c 10 -> starts demo single threaded start/stop with 10 channels"); System.out.println("\tjava o.a.c.t.d.CoordinationDemo -c 7 -t true -s 1000 -sc 50-> starts demo multi threaded start/stop with 7 channels and 1 second sleep time between events and 50 lines to clear screen"); System.out.println("\tjava o.a.c.t.d.CoordinationDemo -t true -p 12 -> starts demo multi threaded start/stop with 5 channels and only prints the EVT_CONF_RX event"); System.out.println(); } public static void main(String[] args) throws Exception { CoordinationDemo demo = new CoordinationDemo(); run(args,demo); } public static String leftfill(String value, int length, String ch) { return fill(value,length,ch,true); } public static String rightfill(String value, int length, String ch) { return fill(value,length,ch,false); } public static String fill(String value, int length, String ch, boolean left) { StringBuilder buf = new StringBuilder(); if ( !left ) buf.append(value.trim()); for (int i=value.trim().length(); i<length; i++ ) buf.append(ch); if ( left ) buf.append(value.trim()); return buf.toString(); } public static class Status { public CoordinationDemo parent; public GroupChannel channel; NonBlockingCoordinator interceptor = null; public String status; public Exception error; public String startstatus = "new"; public Status(CoordinationDemo parent) { this.parent = parent; } public String getStatusLine() { //member - 30 //running- 10 //coord - 30 //view-id - 24 //view count - 8 StringBuilder buf = new StringBuilder(); String local = ""; String coord = ""; String viewId = ""; String count = "0"; if ( channel != null ) { Member lm = channel.getLocalMember(false); local = lm!=null?lm.getName():""; coord = interceptor!=null && interceptor.getCoordinator()!=null?interceptor.getCoordinator().getName():""; if (interceptor != null) { viewId = getByteString(interceptor.getViewId()!=null?interceptor.getViewId().getBytes():new byte[0]); count = String.valueOf(interceptor.getView().length); } } buf.append(leftfill(local,30," ")); buf.append(leftfill(startstatus, 10, " ")); buf.append(leftfill(coord, 30, " ")); buf.append(leftfill(viewId, 24, " ")); buf.append(leftfill(count, 8, " ")); buf.append("\n"); buf.append("Status:"+status); buf.append("\n"); return buf.toString(); } public String getByteString(byte[] b) { if ( b == null ) return "{}"; return Arrays.toString(b,0,Math.min(b.length,4)); } public void start() { try { if ( channel == null ) { channel = createChannel(); startstatus = "starting"; channel.start(Channel.DEFAULT); startstatus = "running"; } else { status = "Channel already started."; } } catch ( Exception x ) { synchronized (System.err) { System.err.println("Start failed:"); StackTraceElement[] els = x.getStackTrace(); for (StackTraceElement el : els) System.err.println(el.toString()); } status = "Start failed:"+x.getMessage(); error = x; startstatus = "failed"; try { channel.stop(Channel.DEFAULT);}catch(Exception ignore){ // Ignore } channel = null; interceptor = null; } } public void stop() { try { if ( channel != null ) { channel.stop(Channel.DEFAULT); status = "Channel Stopped"; } else { status = "Channel Already Stopped"; } }catch ( Exception x ) { synchronized (System.err) { System.err.println("Stop failed:"); StackTraceElement[] els = x.getStackTrace(); for (StackTraceElement el : els) System.err.println(el.toString()); } status = "Stop failed:"+x.getMessage(); error = x; }finally { startstatus = "stopped"; channel = null; interceptor = null; } } public GroupChannel createChannel() { channel = new GroupChannel(); ((ReceiverBase)channel.getChannelReceiver()).setAutoBind(100); interceptor = new NonBlockingCoordinator() { @Override public void fireInterceptorEvent(InterceptorEvent event) { status = event.getEventTypeDesc(); int type = event.getEventType(); boolean display = VIEW_EVENTS[type]; if ( display ) parent.printScreen(); try { Thread.sleep(SLEEP_TIME); }catch ( Exception x){ // Ignore } } }; channel.addInterceptor(interceptor); channel.addInterceptor(new TcpFailureDetector()); channel.addInterceptor(new MessageDispatchInterceptor()); return channel; } } }
package io.github.talelin.latticy.laver.model; import lombok.Data; import java.util.List; @Data public class SpuDetailDO extends SpuDO{ private String categoryName; private String sketchSpecKeyName; private String defaultSkuTitle; private List<String> spuImgList; private List<String> spuDetailImgList; }
package com.mnt.tools.dep; import com.alibaba.fastjson.annotation.JSONField; import java.io.Serializable; import java.util.Date; /** * dto基类 * * @author jiangbiao * @Date 2017年4月18日上午11:37:21 */ @SuppressWarnings("serial") public class GenericDomain<PK> implements Serializable { protected PK id; //id protected String userCreate;//创建用户 protected String userModified;//修改用户 @JSONField(format = "yyyy-MM-dd") protected Date gmtCreate;//创建日期 @JSONField(format = "yyyy-MM-dd") protected Date gmtModified;//修改日期 protected String remark;//备注 protected boolean delFlag;//删除标记 public PK getId() { return id; } public void setId(PK id) { this.id = id; } public String getUserCreate() { return userCreate; } public void setUserCreate(String userCreate) { this.userCreate = userCreate == null ? null : userCreate.trim(); } public String getUserModified() { return userModified; } public void setUserModified(String userModified) { this.userModified = userModified == null ? null : userModified.trim(); } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } public boolean isDelFlag() { return delFlag; } public void setDelFlag(boolean delFlag) { this.delFlag = delFlag; } }
package com.bstek.bdf3.autoconfigure.multitenant; import java.lang.reflect.Method; import org.malagu.multitenant.domain.Organization; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.security.core.context.SecurityContextHolder; import com.bstek.bdf3.security.orm.OrganizationSupport; /** * @author Kevin Yang (mailto:kevin.yang@bstek.com) * @since 2016年8月14日 */ public class OrganizationKeyGenerator implements KeyGenerator { @Override public Object generate(Object target, Method method, Object... params) { String organizationId = ""; if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null) { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof OrganizationSupport) { Organization organization = ((OrganizationSupport) principal).getOrganization(); if (organization != null) { organizationId = organization.getId(); } } } return organizationId; } }
/* * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * * @summary converted from VM Testbase nsk/jdb/pop_exception/pop_exception001. * VM Testbase keywords: [jpda, jdb] * VM Testbase readme: * DECSRIPTION * Test for cr 6972759 "Step over not working after thrown exception and Pop" * COMMENTS * * @library /vmTestbase * /test/lib * @build nsk.jdb.pop_exception.pop_exception001.pop_exception001a * @run main/othervm * nsk.jdb.pop_exception.pop_exception001.pop_exception001 * -arch=${os.family}-${os.simpleArch} * -waittime=5 * -debugee.vmkind=java * -transport.address=dynamic * -jdb=${test.jdk}/bin/jdb * -java.options="${test.vm.opts} ${test.java.opts}" * -workdir=. * -debugee.vmkeys="${test.vm.opts} ${test.java.opts}" */ package nsk.jdb.pop_exception.pop_exception001; import nsk.share.*; import nsk.share.jdb.*; import java.io.*; import java.util.*; public class pop_exception001 extends JdbTest { static final String PACKAGE_NAME = "nsk.jdb.pop_exception.pop_exception001"; static final String TEST_CLASS = PACKAGE_NAME + ".pop_exception001"; static final String DEBUGGEE_CLASS = TEST_CLASS + "a"; static final String FIRST_BREAK = DEBUGGEE_CLASS + ".main"; static final String LAST_BREAK = DEBUGGEE_CLASS + ".lastBreak"; public static void main (String argv[]) { System.exit(run(argv, System.out) + JCK_STATUS_BASE); } public static int run(String argv[], PrintStream out) { debuggeeClass = DEBUGGEE_CLASS; firstBreak = FIRST_BREAK; lastBreak = LAST_BREAK; return new pop_exception001().runTest(argv, out); } protected void runCases() { jdb.receiveReplyFor(JdbCommand._catch + "java.lang.NullPointerException"); jdb.receiveReplyFor(JdbCommand.cont); //exception jdb.receiveReplyFor(JdbCommand.pop); jdb.receiveReplyFor(JdbCommand.pop); jdb.receiveReplyFor(JdbCommand.ignore + "java.lang.NullPointerException"); jdb.receiveReplyFor(JdbCommand.step); jdb.receiveReplyFor(JdbCommand.next); jdb.receiveReplyFor(JdbCommand.next); String[] reply = jdb.receiveReplyFor(JdbCommand.next); jdb.quit(); checkJdbReply(reply); } private void checkJdbReply(String[] jdbReply) { String replyString = ""; for(String s: jdbReply) { replyString += s; if(s.contains("line=")){ if(!s.contains("line=" + pop_exception001a.expectedFinish)) { throw new Failure("FAILED: Expected location: line=" + pop_exception001a.expectedFinish + "\n found: " + s); } else { return; } } } throw new Failure("FAILED: Couldn't determinate finish position: " + replyString); } }
/* * 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.pinterest.secor.common; import io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient; import io.confluent.kafka.schemaregistry.client.SchemaMetadata; import io.confluent.kafka.schemaregistry.client.SchemaRegistryClient; import io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException; import io.confluent.kafka.serializers.KafkaAvroDeserializer; import io.confluent.kafka.serializers.KafkaAvroSerializer; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; public class SecorSchemaRegistryClient implements AvroSchemaRegistry { private static final Logger LOG = LoggerFactory.getLogger(SecorSchemaRegistryClient.class); protected KafkaAvroDeserializer deserializer; protected KafkaAvroSerializer serializer; private final static Map<String, Schema> schemas = new ConcurrentHashMap<>(); protected SchemaRegistryClient schemaRegistryClient; public SecorSchemaRegistryClient(SecorConfig config) { try { Properties props = new Properties(); props.put("schema.registry.url", config.getSchemaRegistryUrl()); schemaRegistryClient = new CachedSchemaRegistryClient(config.getSchemaRegistryUrl(), 30); init(config); } catch (Exception e) { LOG.error("Error initalizing schema registry", e); throw new RuntimeException(e); } } //Allows the SchemaRegistryClient to be mocked in unit tests protected void init(SecorConfig config) { deserializer = new KafkaAvroDeserializer(schemaRegistryClient); serializer = new KafkaAvroSerializer(schemaRegistryClient); } public GenericRecord deserialize(String topic, byte[] message) { if (message.length == 0) { message = null; } GenericRecord record = (GenericRecord) deserializer.deserialize(topic, message); if (record != null) { Schema schema = record.getSchema(); schemas.put(topic, schema); } return record; } /** * Get Avro schema of a topic. It uses the cache that either is set by calling {@link #deserialize(String, byte[])} * or querying this method to avoid hitting Schema Registry for each call. * It uses standard "subject name" strategy and it is topic_name-value. * * @param topic a Kafka topic to query the schema for * @return Schema object for the topic * @throws IllegalStateException if there is no schema registered for this topic or it is not able to fetch it */ public Schema getSchema(String topic) { Schema schema = schemas.get(topic); if (schema == null) { try { SchemaMetadata schemaMetadata = schemaRegistryClient.getLatestSchemaMetadata(topic + "-value"); schema = schemaRegistryClient.getByID(schemaMetadata.getId()); schemas.put(topic, schema); } catch (IOException e) { throw new IllegalStateException("Unable to get Avro schema not found for topic " + topic); } catch (RestClientException e) { throw new IllegalStateException("Avro schema not found for topic " + topic); } } return schema; } @Override public byte[] serialize(String topic, GenericRecord record) throws IOException { return serializer.serialize(topic, record); } }
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_0361 { }
package pk.likhari.models; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class AuthorJSON implements Serializable { private static final long serialVersionUID = -6099312954099962806L; public static String strdescription="description"; public static String strdescription_urdu="description_urdu"; public static String strid="id"; public static String strlogo_large="logo_large"; public static String strlogo_small="logo_small"; public static String strname="name"; public static String strname_ur="name_ur"; public static String strno_of_followers="no_of_followers"; public static String strno_of_views="no_of_views"; public String description; public String description_urdu; public String id; public String logo_large; public String logo_small; public String name; public String name_ur; public String no_of_followers; public String no_of_views; public AuthorJSON(){ this.description= ""; this.description_urdu= ""; this.id= ""; this.logo_large= ""; this.logo_small= ""; this.name= ""; this.name_ur= ""; this.no_of_followers= ""; this.no_of_views= ""; } public static List<AuthorJSON> parse(JSONArray jSonarray) { List<AuthorJSON> authors = new ArrayList<AuthorJSON>(); for(int i=0;i<jSonarray.length();i++) { try { AuthorJSON author = AuthorJSON.parse(jSonarray.getJSONObject(i)); authors.add(author); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } return authors; } public static AuthorJSON parse(JSONObject jSonObj) { AuthorJSON author = new AuthorJSON(); try { author.description= jSonObj.getString(strdescription); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { author.description_urdu= jSonObj.getString(strdescription_urdu); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { author.id= jSonObj.getString(strid); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { author.logo_large= jSonObj.getString(strlogo_large); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { author.logo_small= jSonObj.getString(strlogo_small); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { author.name= jSonObj.getString(strname); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { author.name_ur= jSonObj.getString(strname_ur); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { author.no_of_followers= jSonObj.getString(strno_of_followers); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { author.no_of_views= jSonObj.getString(strno_of_views); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return author; } }
/* Copyright 2002-2007 MySQL AB, 2008 Sun Microsystems All rights reserved. Use is subject to license terms. The MySQL Connector/J is licensed under the terms of the GPL, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPL as it is applied to this software, see the FLOSS License Exception available on mysql.com. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program 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 for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.jdbc; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.mysql.jdbc.profiler.ProfilerEvent; import com.mysql.jdbc.profiler.ProfilerEventHandler; import com.mysql.jdbc.profiler.ProfilerEventHandlerFactory; /** * Allows streaming of MySQL data. * * @author dgan * @version $Id$ */ public class RowDataDynamic implements RowData { class OperationNotSupportedException extends SQLException { OperationNotSupportedException() { super( Messages.getString("RowDataDynamic.10"), SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$ } } private int columnCount; private Field[] metadata; private int index = -1; private MysqlIO io; private boolean isAfterEnd = false; private boolean noMoreRows = false; private boolean isBinaryEncoded = false; private ResultSetRow nextRow; private ResultSetImpl owner; private boolean streamerClosed = false; private boolean wasEmpty = false; // we don't know until we attempt to traverse private boolean useBufferRowExplicit; private boolean moreResultsExisted; private ExceptionInterceptor exceptionInterceptor; /** * Creates a new RowDataDynamic object. * * @param io * the connection to MySQL that this data is coming from * @param metadata * the metadata that describe this data * @param isBinaryEncoded * is this data in native format? * @param colCount * the number of columns * @throws SQLException * if the next record can not be found */ public RowDataDynamic(MysqlIO io, int colCount, Field[] fields, boolean isBinaryEncoded) throws SQLException { this.io = io; this.columnCount = colCount; this.isBinaryEncoded = isBinaryEncoded; this.metadata = fields; this.exceptionInterceptor = this.io.getExceptionInterceptor(); this.useBufferRowExplicit = MysqlIO.useBufferRowExplicit(this.metadata); } /** * Adds a row to this row data. * * @param row * the row to add * @throws SQLException * if a database error occurs */ public void addRow(ResultSetRow row) throws SQLException { notSupported(); } /** * Moves to after last. * * @throws SQLException * if a database error occurs */ public void afterLast() throws SQLException { notSupported(); } /** * Moves to before first. * * @throws SQLException * if a database error occurs */ public void beforeFirst() throws SQLException { notSupported(); } /** * Moves to before last so next el is the last el. * * @throws SQLException * if a database error occurs */ public void beforeLast() throws SQLException { notSupported(); } /** * We're done. * * @throws SQLException * if a database error occurs */ public void close() throws SQLException { // Belt and suspenders here - if we don't // have a reference to the connection // it's more than likely dead/gone and we // won't be able to consume rows anyway Object mutex = this; ConnectionImpl conn = null; if (this.owner != null) { conn = this.owner.connection; if (conn != null) { mutex = conn.getMutex(); } } boolean hadMore = false; int howMuchMore = 0; synchronized (mutex) { // drain the rest of the records. while (next() != null) { hadMore = true; howMuchMore++; if (howMuchMore % 100 == 0) { Thread.yield(); } } if (conn != null) { if (!conn.getClobberStreamingResults() && conn.getNetTimeoutForStreamingResults() > 0) { String oldValue = conn .getServerVariable("net_write_timeout"); if (oldValue == null || oldValue.length() == 0) { oldValue = "60"; // the current default } this.io.clearInputStream(); java.sql.Statement stmt = null; try { stmt = conn.createStatement(); ((com.mysql.jdbc.StatementImpl)stmt).executeSimpleNonQuery(conn, "SET net_write_timeout=" + oldValue); } finally { if (stmt != null) { stmt.close(); } } } if (conn.getUseUsageAdvisor()) { if (hadMore) { ProfilerEventHandler eventSink = ProfilerEventHandlerFactory .getInstance(conn); eventSink .consumeEvent(new ProfilerEvent( ProfilerEvent.TYPE_WARN, "", //$NON-NLS-1$ this.owner.owningStatement == null ? "N/A" : this.owner.owningStatement.currentCatalog, //$NON-NLS-1$ this.owner.connectionId, this.owner.owningStatement == null ? -1 : this.owner.owningStatement .getId(), -1, System.currentTimeMillis(), 0, Constants.MILLIS_I18N, null, null, Messages.getString("RowDataDynamic.2") //$NON-NLS-1$ + howMuchMore + Messages .getString("RowDataDynamic.3") //$NON-NLS-1$ + Messages .getString("RowDataDynamic.4") //$NON-NLS-1$ + Messages .getString("RowDataDynamic.5") //$NON-NLS-1$ + Messages .getString("RowDataDynamic.6") //$NON-NLS-1$ + this.owner.pointOfOrigin)); } } } } this.metadata = null; this.owner = null; } /** * Only works on non dynamic result sets. * * @param index * row number to get at * @return row data at index * @throws SQLException * if a database error occurs */ public ResultSetRow getAt(int ind) throws SQLException { notSupported(); return null; } /** * Returns the current position in the result set as a row number. * * @return the current row number * @throws SQLException * if a database error occurs */ public int getCurrentRowNumber() throws SQLException { notSupported(); return -1; } /** * @see com.mysql.jdbc.RowData#getOwner() */ public ResultSetInternalMethods getOwner() { return this.owner; } /** * Returns true if another row exsists. * * @return true if more rows * @throws SQLException * if a database error occurs */ public boolean hasNext() throws SQLException { boolean hasNext = (this.nextRow != null); if (!hasNext && !this.streamerClosed) { this.io.closeStreamer(this); this.streamerClosed = true; } return hasNext; } /** * Returns true if we got the last element. * * @return true if after last row * @throws SQLException * if a database error occurs */ public boolean isAfterLast() throws SQLException { return this.isAfterEnd; } /** * Returns if iteration has not occured yet. * * @return true if before first row * @throws SQLException * if a database error occurs */ public boolean isBeforeFirst() throws SQLException { return this.index < 0; } /** * Returns true if the result set is dynamic. * * This means that move back and move forward won't work because we do not * hold on to the records. * * @return true if this result set is streaming from the server */ public boolean isDynamic() { return true; } /** * Has no records. * * @return true if no records * @throws SQLException * if a database error occurs */ public boolean isEmpty() throws SQLException { notSupported(); return false; } /** * Are we on the first row of the result set? * * @return true if on first row * @throws SQLException * if a database error occurs */ public boolean isFirst() throws SQLException { notSupported(); return false; } /** * Are we on the last row of the result set? * * @return true if on last row * @throws SQLException * if a database error occurs */ public boolean isLast() throws SQLException { notSupported(); return false; } /** * Moves the current position relative 'rows' from the current position. * * @param rows * the relative number of rows to move * @throws SQLException * if a database error occurs */ public void moveRowRelative(int rows) throws SQLException { notSupported(); } /** * Returns the next row. * * @return the next row value * @throws SQLException * if a database error occurs */ public ResultSetRow next() throws SQLException { nextRecord(); if (this.nextRow == null && !this.streamerClosed && !this.moreResultsExisted) { this.io.closeStreamer(this); this.streamerClosed = true; } if (this.nextRow != null) { if (this.index != Integer.MAX_VALUE) { this.index++; } } return this.nextRow; } private void nextRecord() throws SQLException { try { if (!this.noMoreRows) { this.nextRow = this.io.nextRow(this.metadata, this.columnCount, this.isBinaryEncoded, java.sql.ResultSet.CONCUR_READ_ONLY, true, this.useBufferRowExplicit, true, null); if (this.nextRow == null) { this.noMoreRows = true; this.isAfterEnd = true; this.moreResultsExisted = this.io.tackOnMoreStreamingResults(this.owner); if (this.index == -1) { this.wasEmpty = true; } } } else { this.isAfterEnd = true; } } catch (SQLException sqlEx) { if (sqlEx instanceof StreamingNotifiable) { ((StreamingNotifiable)sqlEx).setWasStreamingResults(); } // don't wrap SQLExceptions throw sqlEx; } catch (Exception ex) { String exceptionType = ex.getClass().getName(); String exceptionMessage = ex.getMessage(); exceptionMessage += Messages.getString("RowDataDynamic.7"); //$NON-NLS-1$ exceptionMessage += Util.stackTraceToString(ex); SQLException sqlEx = SQLError.createSQLException( Messages.getString("RowDataDynamic.8") //$NON-NLS-1$ + exceptionType + Messages.getString("RowDataDynamic.9") + exceptionMessage, SQLError.SQL_STATE_GENERAL_ERROR, this.exceptionInterceptor); //$NON-NLS-1$ sqlEx.initCause(ex); throw sqlEx; } } private void notSupported() throws SQLException { throw new OperationNotSupportedException(); } /** * Removes the row at the given index. * * @param index * the row to move to * @throws SQLException * if a database error occurs */ public void removeRow(int ind) throws SQLException { notSupported(); } /** * Moves the current position in the result set to the given row number. * * @param rowNumber * row to move to * @throws SQLException * if a database error occurs */ public void setCurrentRow(int rowNumber) throws SQLException { notSupported(); } /** * @see com.mysql.jdbc.RowData#setOwner(com.mysql.jdbc.ResultSetInternalMethods) */ public void setOwner(ResultSetImpl rs) { this.owner = rs; } /** * Only works on non dynamic result sets. * * @return the size of this row data */ public int size() { return RESULT_SET_SIZE_UNKNOWN; } public boolean wasEmpty() { return this.wasEmpty; } public void setMetadata(Field[] metadata) { this.metadata = metadata; } }
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.verifier.event; /* * Class org.jboss.verifier.event.Library (refer Class org.gjt.lindfors.util.Library at www.gjt.org) * Copyright (C) 1999 Juha Lindfors * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * This package and its source code is available at www.jboss.org * $Id: Library.java 3217 2007-12-06 11:28:57Z csaldanh@redhat.com $ * * You can reach the author by sending email to jpl@gjt.org or * directly to jplindfo@helsinki.fi. */ /** * Collection of miscellaneous utility methods. * <p> * For more detailed documentation, refer to the * <a href="http://www.gjt.org/%7ejpl/org_gjt_lindfors_util/index.html"> * Util Library Developer's Guide</a> * * @author Juha Lindfors * @version $Revision: 1.1 $ * @since JDK1.1 */ public class Library { private Library() {} /** * Returns the class name of an object. This method returns only the * name of the class, not a fully qualified class name with package * information. For fully qualified class name, use * <code>getClass().getName()</code>. * * @param obj object whose class name is wanted * * @return object's class name, without package information * * @see java.lang.Object#getClass() */ public static String getClassName(Object obj) { String str = obj.getClass().getName(); int index = str.lastIndexOf('.'); return str.substring(index+1); } }
package org.kuse.payloadbuilder.catalog.jdbc; import java.sql.SQLException; import org.kuse.payloadbuilder.core.catalog.CatalogException; /** Connection exception thrown for when an connection couldn't be created */ class ConnectionException extends CatalogException { private final SQLException exception; ConnectionException(String catalogAlias, SQLException exception) { super(catalogAlias, exception.getMessage()); this.exception = exception; } SQLException getException() { return exception; } }
package ansj.sun.bloomFilter.filter; public class PJWFilter extends AbstractFilter { public PJWFilter(long maxValue, int MACHINENUM) throws Exception { super(maxValue, MACHINENUM); } public PJWFilter(long maxValue) { super(maxValue); } public long myHashCode(String str) { int BitsInUnsignedInt = 32; int ThreeQuarters = (BitsInUnsignedInt * 3) / 4; int OneEighth = BitsInUnsignedInt / 8; int HighBits = 0xFFFFFFFF << (BitsInUnsignedInt - OneEighth); int hash = 0; int test = 0; for (int i = 0; i < str.length(); i++) { hash = (hash << OneEighth) + str.charAt(i); if ((test = hash & HighBits) != 0) { hash = ((hash ^ (test >> ThreeQuarters)) & (~HighBits)); } } return dealHashcode(hash); } }
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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.ignite.ml.inference.builder; import java.io.Serializable; import org.apache.ignite.ml.inference.Model; import org.apache.ignite.ml.inference.parser.ModelParser; import org.apache.ignite.ml.inference.reader.ModelReader; /** * Implementation of synchronous inference model builder that builds a model processed locally in a single thread. */ public class SingleModelBuilder implements SyncModelBuilder { /** {@inheritDoc} */ @Override public <I extends Serializable, O extends Serializable, M extends Model<I, O>> M build(ModelReader reader, ModelParser<I, O, M> parser) { return parser.parse(reader.read()); } }
package io.swagger.codegen; import io.swagger.models.*; import io.swagger.models.parameters.BodyParameter; import io.swagger.models.parameters.Parameter; import io.swagger.models.properties.*; import io.swagger.util.Json; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class InlineModelResolver { private Swagger swagger; private boolean skipMatches; static Logger LOGGER = LoggerFactory.getLogger(InlineModelResolver.class); Map<String, Model> addedModels = new HashMap<String, Model>(); Map<String, String> generatedSignature = new HashMap<String, String>(); public void flatten(Swagger swagger) { this.swagger = swagger; if (swagger.getDefinitions() == null) { swagger.setDefinitions(new HashMap<String, Model>()); } // operations Map<String, Path> paths = swagger.getPaths(); Map<String, Model> models = swagger.getDefinitions(); if (paths != null) { for (String pathname : paths.keySet()) { Path path = paths.get(pathname); for (Operation operation : path.getOperations()) { List<Parameter> parameters = operation.getParameters(); if (parameters != null) { for (Parameter parameter : parameters) { if (parameter instanceof BodyParameter) { BodyParameter bp = (BodyParameter) parameter; if (bp.getSchema() != null) { Model model = bp.getSchema(); if (model instanceof ModelImpl) { ModelImpl obj = (ModelImpl) model; if (obj.getType() == null || "object".equals(obj.getType())) { if (obj.getProperties() != null && obj.getProperties().size() > 0) { flattenProperties(obj.getProperties(), pathname); String modelName = resolveModelName(obj.getTitle(), bp.getName(), operation.getOperationId()); bp.setSchema(new RefModel(modelName)); addGenerated(modelName, model); swagger.addDefinition(modelName, model); } } } else if (model instanceof ArrayModel) { ArrayModel am = (ArrayModel) model; Property inner = am.getItems(); if (inner instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) inner; if (op.getProperties() != null && op.getProperties().size() > 0) { flattenProperties(op.getProperties(), pathname); String modelName = resolveModelName(op.getTitle(), bp.getName(), operation.getOperationId()); Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { am.setItems(new RefProperty(existing)); } else { am.setItems(new RefProperty(modelName)); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); } } } } } } } } Map<String, Response> responses = operation.getResponses(); if (responses != null) { for (String key : responses.keySet()) { Response response = responses.get(key); if (response.getSchema() != null) { Property property = response.getSchema(); if (property instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) property; if (op.getProperties() != null && op.getProperties().size() > 0) { String modelName = resolveModelName(op.getTitle(), "inline_response_" + key, operation.getOperationId()); Model model = modelFromProperty(op, modelName); String existing = matchGenerated(model); if (existing != null) { response.setSchema(this.makeRefProperty(existing, property)); } else { response.setSchema(this.makeRefProperty(modelName, property)); addGenerated(modelName, model); swagger.addDefinition(modelName, model); } } } else if (property instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) property; Property inner = ap.getItems(); if (inner instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) inner; if (op.getProperties() != null && op.getProperties().size() > 0) { flattenProperties(op.getProperties(), pathname); String modelName = resolveModelName(op.getTitle(),"inline_response_" + key, operation.getOperationId()); Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { ap.setItems(this.makeRefProperty(existing, op)); } else { ap.setItems(this.makeRefProperty(modelName, op)); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); } } } } else if (property instanceof MapProperty) { MapProperty mp = (MapProperty) property; Property innerProperty = mp.getAdditionalProperties(); if (innerProperty instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) innerProperty; if (op.getProperties() != null && op.getProperties().size() > 0) { flattenProperties(op.getProperties(), pathname); String modelName = resolveModelName(op.getTitle(), "inline_response_" + key, operation.getOperationId()); Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { mp.setAdditionalProperties(new RefProperty(existing)); } else { mp.setAdditionalProperties(new RefProperty(modelName)); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); } } } } } } } } } } // definitions if (models != null) { List<String> modelNames = new ArrayList<String>(models.keySet()); for (String modelName : modelNames) { Model model = models.get(modelName); if (model instanceof ModelImpl) { ModelImpl m = (ModelImpl) model; Map<String, Property> properties = m.getProperties(); flattenProperties(properties, modelName); fixStringModel(m); } else if (model instanceof ArrayModel) { ArrayModel m = (ArrayModel) model; Property inner = m.getItems(); if (inner instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) inner; if (op.getProperties() != null && op.getProperties().size() > 0) { String innerModelName = resolveModelName(op.getTitle(), modelName + "_inner", null); Model innerModel = modelFromProperty(op, innerModelName); String existing = matchGenerated(innerModel); if (existing == null) { swagger.addDefinition(innerModelName, innerModel); addGenerated(innerModelName, innerModel); m.setItems(new RefProperty(innerModelName)); } else { m.setItems(new RefProperty(existing)); } } } } else if (model instanceof ComposedModel) { ComposedModel m = (ComposedModel) model; if (m.getChild() != null) { Map<String, Property> properties = m.getChild().getProperties(); flattenProperties(properties, modelName); } } } } } /** * This function fix models that are string (mostly enum). Before this fix, the example * would look something like that in the doc: "\"example from def\"" * @param m Model implementation */ private void fixStringModel(ModelImpl m) { if (m.getType() != null && m.getType().equals("string") && m.getExample() != null) { String example = m.getExample().toString(); if (example.substring(0, 1).equals("\"") && example.substring(example.length() - 1).equals("\"")) { m.setExample(example.substring(1, example.length() - 1)); } } } private String resolveModelName(String title, String key, String operationID) { if (title == null && operationID ==null) { return uniqueName(key); } else if (title != null){ return uniqueName(title); } else{ return uniqueName(operationID); } } public String matchGenerated(Model model) { if (this.skipMatches) { return null; } String json = Json.pretty(model); if (generatedSignature.containsKey(json)) { return generatedSignature.get(json); } return null; } public void addGenerated(String name, Model model) { generatedSignature.put(Json.pretty(model), name); } public String uniqueName(String key) { int count = 0; boolean done = false; key = key.replaceAll("[^a-z_\\.A-Z0-9 ]", ""); // FIXME: a parameter // should not be // assigned. Also declare // the methods parameters // as 'final'. while (!done) { String name = key; if (count > 0) { name = key + "_" + count; } if (swagger.getDefinitions() == null) { return name; } else if (!swagger.getDefinitions().containsKey(name)) { return name; } count += 1; } return key; } public void flattenProperties(Map<String, Property> properties, String path) { if (properties == null) { return; } Map<String, Property> propsToUpdate = new HashMap<String, Property>(); Map<String, Model> modelsToAdd = new HashMap<String, Model>(); for (String key : properties.keySet()) { Property property = properties.get(key); if (property instanceof ObjectProperty && ((ObjectProperty) property).getProperties() != null && ((ObjectProperty) property).getProperties().size() > 0) { ObjectProperty op = (ObjectProperty) property; String modelName = resolveModelName(op.getTitle(), path + "_" + key, null); Model model = modelFromProperty(op, modelName); String existing = matchGenerated(model); if (existing != null) { propsToUpdate.put(key, new RefProperty(existing)); } else { propsToUpdate.put(key, new RefProperty(modelName)); modelsToAdd.put(modelName, model); addGenerated(modelName, model); swagger.addDefinition(modelName, model); } } else if (property instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) property; Property inner = ap.getItems(); if (inner instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) inner; if (op.getProperties() != null && op.getProperties().size() > 0) { flattenProperties(op.getProperties(), path); String modelName = resolveModelName(op.getTitle(), path + "_" + key, null); Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { ap.setItems(new RefProperty(existing)); } else { ap.setItems(new RefProperty(modelName)); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); } } } } else if (property instanceof MapProperty) { MapProperty mp = (MapProperty) property; Property inner = mp.getAdditionalProperties(); if (inner instanceof ObjectProperty) { ObjectProperty op = (ObjectProperty) inner; if (op.getProperties() != null && op.getProperties().size() > 0) { flattenProperties(op.getProperties(), path); String modelName = resolveModelName(op.getTitle(), path + "_" + key, null); Model innerModel = modelFromProperty(op, modelName); String existing = matchGenerated(innerModel); if (existing != null) { mp.setAdditionalProperties(new RefProperty(existing)); } else { mp.setAdditionalProperties(new RefProperty(modelName)); addGenerated(modelName, innerModel); swagger.addDefinition(modelName, innerModel); } } } } } if (propsToUpdate.size() > 0) { for (String key : propsToUpdate.keySet()) { properties.put(key, propsToUpdate.get(key)); } } for (String key : modelsToAdd.keySet()) { swagger.addDefinition(key, modelsToAdd.get(key)); this.addedModels.put(key, modelsToAdd.get(key)); } } @SuppressWarnings("static-method") public Model modelFromProperty(ArrayProperty object, @SuppressWarnings("unused") String path) { String description = object.getDescription(); String example = null; Object obj = object.getExample(); if (obj != null) { example = obj.toString(); } Property inner = object.getItems(); if (inner instanceof ObjectProperty) { ArrayModel model = new ArrayModel(); model.setDescription(description); model.setExample(example); model.setItems(object.getItems()); return model; } return null; } public Model modelFromProperty(ObjectProperty object, String path) { String description = object.getDescription(); String example = null; Object obj = object.getExample(); if (obj != null) { example = obj.toString(); } String name = object.getName(); Xml xml = object.getXml(); Map<String, Property> properties = object.getProperties(); ModelImpl model = new ModelImpl(); model.setDescription(description); model.setExample(example); model.setName(name); model.setXml(xml); if (properties != null) { flattenProperties(properties, path); model.setProperties(properties); } return model; } @SuppressWarnings("static-method") public Model modelFromProperty(MapProperty object, @SuppressWarnings("unused") String path) { String description = object.getDescription(); String example = null; Object obj = object.getExample(); if (obj != null) { example = obj.toString(); } ArrayModel model = new ArrayModel(); model.setDescription(description); model.setExample(example); model.setItems(object.getAdditionalProperties()); return model; } /** * Make a RefProperty * * @param ref new property name * @param property Property * @return */ public Property makeRefProperty(String ref, Property property) { RefProperty newProperty = new RefProperty(ref); this.copyVendorExtensions(property, newProperty); return newProperty; } /** * Copy vendor extensions from Property to another Property * * @param source source property * @param target target property */ public void copyVendorExtensions(Property source, AbstractProperty target) { Map<String, Object> vendorExtensions = source.getVendorExtensions(); for (String extName : vendorExtensions.keySet()) { target.setVendorExtension(extName, vendorExtensions.get(extName)); } } public boolean isSkipMatches() { return skipMatches; } public void setSkipMatches(boolean skipMatches) { this.skipMatches = skipMatches; } }
package ch.fetz.ServerManager.spigot.Utils; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.bukkit.Bukkit; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.ServicePriority; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.zip.GZIPOutputStream; /** * bStats collects some data for plugin authors. * <p> * Check out https://bStats.org/ to learn more about bStats! */ @SuppressWarnings({"WeakerAccess", "unused"}) public class SpigotMetrics { static { // You can use the property to disable the check in your test environment if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D final String defaultPackage = new String( new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); // We want to make sure nobody just copy & pastes the example and use the wrong package names if (SpigotMetrics.class.getPackage().getName().equals(defaultPackage) || SpigotMetrics.class.getPackage().getName().equals(examplePackage)) { throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); } } } // The version of this bStats class public static final int B_STATS_VERSION = 1; // The url to which the data is sent private static final String URL = "https://bStats.org/submitData/bukkit"; // Is bStats enabled on this server? private final boolean enabled; // Should failed requests be logged? private static boolean logFailedRequests; // Should the sent data be logged? private static boolean logSentData; // Should the response text be logged? private static boolean logResponseStatusText; // The uuid of the server private static String serverUUID; // The plugin private final Plugin plugin; // A list with all custom charts private final List<CustomChart> charts = new ArrayList<>(); /** * Class constructor. * * @param plugin The plugin which stats should be submitted. */ public SpigotMetrics(Plugin plugin) { if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null!"); } this.plugin = plugin; // Get the config file File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); File configFile = new File(bStatsFolder, "config.yml"); YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); // Check if the config file exists if (!config.isSet("serverUuid")) { // Add default values config.addDefault("enabled", true); // Every server gets it's unique random id. config.addDefault("serverUuid", UUID.randomUUID().toString()); // Should failed request be logged? config.addDefault("logFailedRequests", false); // Should the sent data be logged? config.addDefault("logSentData", false); // Should the response text be logged? config.addDefault("logResponseStatusText", false); // Inform the server owners about bStats config.options().header( "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + "To honor their work, you should not disable it.\n" + "This has nearly no effect on the server performance!\n" + "Check out https://bStats.org/ to learn more :)" ).copyDefaults(true); try { config.save(configFile); } catch (IOException ignored) { } } // Load the data enabled = config.getBoolean("enabled", true); serverUUID = config.getString("serverUuid"); logFailedRequests = config.getBoolean("logFailedRequests", false); logSentData = config.getBoolean("logSentData", false); logResponseStatusText = config.getBoolean("logResponseStatusText", false); if (enabled) { boolean found = false; // Search for all other bStats Metrics classes to see if we are the first one for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) { try { service.getField("B_STATS_VERSION"); // Our identifier :) found = true; // We aren't the first break; } catch (NoSuchFieldException ignored) { } } // Register our service Bukkit.getServicesManager().register(SpigotMetrics.class, this, plugin, ServicePriority.Normal); if (!found) { // We are the first! startSubmitting(); } } } /** * Checks if bStats is enabled. * * @return Whether bStats is enabled or not. */ public boolean isEnabled() { return enabled; } /** * Adds a custom chart. * * @param chart The chart to add. */ public void addCustomChart(CustomChart chart) { if (chart == null) { throw new IllegalArgumentException("Chart cannot be null!"); } charts.add(chart); } /** * Starts the Scheduler which submits our data every 30 minutes. */ private void startSubmitting() { final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (!plugin.isEnabled()) { // Plugin was disabled timer.cancel(); return; } // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) Bukkit.getScheduler().runTask(plugin, () -> submitData()); } }, 1000 * 60 * 5, 1000 * 60 * 30); // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! // WARNING: Just don't do it! } /** * Gets the plugin specific data. * This method is called using Reflection. * * @return The plugin specific data. */ public JsonObject getPluginData() { JsonObject data = new JsonObject(); String pluginName = plugin.getDescription().getName(); String pluginVersion = plugin.getDescription().getVersion(); data.addProperty("pluginName", pluginName); // Append the name of the plugin data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin JsonArray customCharts = new JsonArray(); for (CustomChart customChart : charts) { // Add the data of the custom charts JsonObject chart = customChart.getRequestJsonObject(); if (chart == null) { // If the chart is null, we skip it continue; } customCharts.add(chart); } data.add("customCharts", customCharts); return data; } /** * Gets the server specific data. * * @return The server specific data. */ private JsonObject getServerData() { // Minecraft specific data int playerAmount; try { // Around MC 1.8 the return type was changed to a collection from an array, // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) ? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size() : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; } catch (Exception e) { playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed } int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; String bukkitVersion = Bukkit.getVersion(); String bukkitName = Bukkit.getName(); // OS/Java specific data String javaVersion = System.getProperty("java.version"); String osName = System.getProperty("os.name"); String osArch = System.getProperty("os.arch"); String osVersion = System.getProperty("os.version"); int coreCount = Runtime.getRuntime().availableProcessors(); JsonObject data = new JsonObject(); data.addProperty("serverUUID", serverUUID); data.addProperty("playerAmount", playerAmount); data.addProperty("onlineMode", onlineMode); data.addProperty("bukkitVersion", bukkitVersion); data.addProperty("bukkitName", bukkitName); data.addProperty("javaVersion", javaVersion); data.addProperty("osName", osName); data.addProperty("osArch", osArch); data.addProperty("osVersion", osVersion); data.addProperty("coreCount", coreCount); return data; } /** * Collects the data and sends it afterwards. */ private void submitData() { final JsonObject data = getServerData(); JsonArray pluginData = new JsonArray(); // Search for all other bStats Metrics classes to get their plugin data for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) { try { service.getField("B_STATS_VERSION"); // Our identifier :) for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) { try { Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); if (plugin instanceof JsonObject) { pluginData.add((JsonObject) plugin); } else { // old bstats version compatibility try { Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); jsonStringGetter.setAccessible(true); String jsonString = (String) jsonStringGetter.invoke(plugin); JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); pluginData.add(object); } } catch (ClassNotFoundException e) { // minecraft version 1.14+ if (logFailedRequests) { this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e); } continue; // continue looping since we cannot do any other thing. } } } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } } } catch (NoSuchFieldException ignored) { } } data.add("plugins", pluginData); // Create a new thread for the connection to the bStats server new Thread(new Runnable() { @Override public void run() { try { // Send the data sendData(plugin, data); } catch (Exception e) { // Something went wrong! :( if (logFailedRequests) { plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); } } } }).start(); } /** * Sends the data to the bStats server. * * @param plugin Any plugin. It's just used to get a logger instance. * @param data The data to send. * @throws Exception If the request failed. */ private static void sendData(Plugin plugin, JsonObject data) throws Exception { if (data == null) { throw new IllegalArgumentException("Data cannot be null!"); } if (Bukkit.isPrimaryThread()) { throw new IllegalAccessException("This method must not be called from the main thread!"); } if (logSentData) { plugin.getLogger().info("Sending data to bStats: " + data.toString()); } HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); // Compress the data to save bandwidth byte[] compressedData = compress(data.toString()); // Add headers connection.setRequestMethod("POST"); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); // Send data connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.write(compressedData); outputStream.flush(); outputStream.close(); InputStream inputStream = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder builder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { builder.append(line); } bufferedReader.close(); if (logResponseStatusText) { plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString()); } } /** * Gzips the given String. * * @param str The string to gzip. * @return The gzipped String. * @throws IOException If the compression failed. */ private static byte[] compress(final String str) throws IOException { if (str == null) { return null; } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(outputStream); gzip.write(str.getBytes(StandardCharsets.UTF_8)); gzip.close(); return outputStream.toByteArray(); } /** * Represents a custom chart. */ public static abstract class CustomChart { // The id of the chart final String chartId; /** * Class constructor. * * @param chartId The id of the chart. */ CustomChart(String chartId) { if (chartId == null || chartId.isEmpty()) { throw new IllegalArgumentException("ChartId cannot be null or empty!"); } this.chartId = chartId; } private JsonObject getRequestJsonObject() { JsonObject chart = new JsonObject(); chart.addProperty("chartId", chartId); try { JsonObject data = getChartData(); if (data == null) { // If the data is null we don't send the chart. return null; } chart.add("data", data); } catch (Throwable t) { if (logFailedRequests) { Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); } return null; } return chart; } protected abstract JsonObject getChartData() throws Exception; } /** * Represents a custom simple pie. */ public static class SimplePie extends CustomChart { private final Callable<String> callable; /** * Class constructor. * * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SimplePie(String chartId, Callable<String> callable) { super(chartId); this.callable = callable; } @Override protected JsonObject getChartData() throws Exception { JsonObject data = new JsonObject(); String value = callable.call(); if (value == null || value.isEmpty()) { // Null = skip the chart return null; } data.addProperty("value", value); return data; } } /** * Represents a custom advanced pie. */ public static class AdvancedPie extends CustomChart { private final Callable<Map<String, Integer>> callable; /** * Class constructor. * * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) { super(chartId); this.callable = callable; } @Override protected JsonObject getChartData() throws Exception { JsonObject data = new JsonObject(); JsonObject values = new JsonObject(); Map<String, Integer> map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } boolean allSkipped = true; for (Map.Entry<String, Integer> entry : map.entrySet()) { if (entry.getValue() == 0) { continue; // Skip this invalid } allSkipped = false; values.addProperty(entry.getKey(), entry.getValue()); } if (allSkipped) { // Null = skip the chart return null; } data.add("values", values); return data; } } /** * Represents a custom drilldown pie. */ public static class DrilldownPie extends CustomChart { private final Callable<Map<String, Map<String, Integer>>> callable; /** * Class constructor. * * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) { super(chartId); this.callable = callable; } @Override public JsonObject getChartData() throws Exception { JsonObject data = new JsonObject(); JsonObject values = new JsonObject(); Map<String, Map<String, Integer>> map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } boolean reallyAllSkipped = true; for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) { JsonObject value = new JsonObject(); boolean allSkipped = true; for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) { value.addProperty(valueEntry.getKey(), valueEntry.getValue()); allSkipped = false; } if (!allSkipped) { reallyAllSkipped = false; values.add(entryValues.getKey(), value); } } if (reallyAllSkipped) { // Null = skip the chart return null; } data.add("values", values); return data; } } /** * Represents a custom single line chart. */ public static class SingleLineChart extends CustomChart { private final Callable<Integer> callable; /** * Class constructor. * * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SingleLineChart(String chartId, Callable<Integer> callable) { super(chartId); this.callable = callable; } @Override protected JsonObject getChartData() throws Exception { JsonObject data = new JsonObject(); int value = callable.call(); if (value == 0) { // Null = skip the chart return null; } data.addProperty("value", value); return data; } } /** * Represents a custom multi line chart. */ public static class MultiLineChart extends CustomChart { private final Callable<Map<String, Integer>> callable; /** * Class constructor. * * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) { super(chartId); this.callable = callable; } @Override protected JsonObject getChartData() throws Exception { JsonObject data = new JsonObject(); JsonObject values = new JsonObject(); Map<String, Integer> map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } boolean allSkipped = true; for (Map.Entry<String, Integer> entry : map.entrySet()) { if (entry.getValue() == 0) { continue; // Skip this invalid } allSkipped = false; values.addProperty(entry.getKey(), entry.getValue()); } if (allSkipped) { // Null = skip the chart return null; } data.add("values", values); return data; } } /** * Represents a custom simple bar chart. */ public static class SimpleBarChart extends CustomChart { private final Callable<Map<String, Integer>> callable; /** * Class constructor. * * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) { super(chartId); this.callable = callable; } @Override protected JsonObject getChartData() throws Exception { JsonObject data = new JsonObject(); JsonObject values = new JsonObject(); Map<String, Integer> map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } for (Map.Entry<String, Integer> entry : map.entrySet()) { JsonArray categoryValues = new JsonArray(); categoryValues.add(entry.getValue()); values.add(entry.getKey(), categoryValues); } data.add("values", values); return data; } } /** * Represents a custom advanced bar chart. */ public static class AdvancedBarChart extends CustomChart { private final Callable<Map<String, int[]>> callable; /** * Class constructor. * * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) { super(chartId); this.callable = callable; } @Override protected JsonObject getChartData() throws Exception { JsonObject data = new JsonObject(); JsonObject values = new JsonObject(); Map<String, int[]> map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } boolean allSkipped = true; for (Map.Entry<String, int[]> entry : map.entrySet()) { if (entry.getValue().length == 0) { continue; // Skip this invalid } allSkipped = false; JsonArray categoryValues = new JsonArray(); for (int categoryValue : entry.getValue()) { categoryValues.add(categoryValue); } values.add(entry.getKey(), categoryValues); } if (allSkipped) { // Null = skip the chart return null; } data.add("values", values); return data; } } }
package edu.unah.poo; public class Carne extends Ingredient{ public Carne(String name, int price, int calories) { super(name, price, calories); } @Override public String getName() { return "carne"; } @Override public int getCalories() { return 15; } @Override public int getPrice() { return 5; } }
/** * Copyright 2015-2017 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package zipkin.storage.elasticsearch.http; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.JsonDataException; import com.squareup.moshi.JsonReader; import com.squareup.moshi.JsonWriter; import java.io.IOException; import okio.Buffer; import okio.ByteString; import zipkin.Annotation; import zipkin.BinaryAnnotation; import zipkin.DependencyLink; import zipkin.Endpoint; import zipkin.Span; import zipkin.internal.Util; import static zipkin.internal.Util.UTF_8; import static zipkin.internal.Util.lowerHexToUnsignedLong; /** * Read-only json adapters resurrected from before we switched to Java 6 as storage components can * be Java 7+ */ final class JsonAdapters { static final JsonAdapter<Span> SPAN_ADAPTER = new JsonAdapter<Span>() { @Override public Span fromJson(JsonReader reader) throws IOException { Span.Builder result = Span.builder(); reader.beginObject(); while (reader.hasNext()) { String nextName = reader.nextName(); if (reader.peek() == JsonReader.Token.NULL) { reader.skipValue(); continue; } switch (nextName) { case "traceId": String traceId = reader.nextString(); if (traceId.length() == 32) { result.traceIdHigh(lowerHexToUnsignedLong(traceId, 0)); } result.traceId(lowerHexToUnsignedLong(traceId)); break; case "name": result.name(reader.nextString()); break; case "id": result.id(Util.lowerHexToUnsignedLong(reader.nextString())); break; case "parentId": result.parentId(Util.lowerHexToUnsignedLong(reader.nextString())); break; case "timestamp": result.timestamp(reader.nextLong()); break; case "duration": result.duration(reader.nextLong()); break; case "annotations": reader.beginArray(); while (reader.hasNext()) { result.addAnnotation(ANNOTATION_ADAPTER.fromJson(reader)); } reader.endArray(); break; case "binaryAnnotations": reader.beginArray(); while (reader.hasNext()) { result.addBinaryAnnotation(BINARY_ANNOTATION_ADAPTER.fromJson(reader)); } reader.endArray(); break; case "debug": result.debug(reader.nextBoolean()); break; default: reader.skipValue(); } } reader.endObject(); return result.build(); } @Override public void toJson(JsonWriter writer, Span value) throws IOException { throw new UnsupportedOperationException(); } }; static final JsonAdapter<Annotation> ANNOTATION_ADAPTER = new JsonAdapter<Annotation>() { @Override public Annotation fromJson(JsonReader reader) throws IOException { Annotation.Builder result = Annotation.builder(); reader.beginObject(); while (reader.hasNext()) { switch (reader.nextName()) { case "timestamp": result.timestamp(reader.nextLong()); break; case "value": result.value(reader.nextString()); break; case "endpoint": result.endpoint(ENDPOINT_ADAPTER.fromJson(reader)); break; default: reader.skipValue(); } } reader.endObject(); return result.build(); } @Override public void toJson(JsonWriter writer, Annotation value) throws IOException { throw new UnsupportedOperationException(); } }; static final JsonAdapter<Endpoint> ENDPOINT_ADAPTER = new JsonAdapter<Endpoint>() { @Override public Endpoint fromJson(JsonReader reader) throws IOException { Endpoint.Builder result = Endpoint.builder(); reader.beginObject(); while (reader.hasNext()) { switch (reader.nextName()) { case "serviceName": result.serviceName(reader.nextString()); break; case "ipv4": case "ipv6": result.parseIp(reader.nextString()); break; case "port": result.port(reader.nextInt()); break; default: reader.skipValue(); } } reader.endObject(); return result.build(); } @Override public void toJson(JsonWriter writer, Endpoint value) throws IOException { throw new UnsupportedOperationException(); } }.nullSafe(); static final JsonAdapter<BinaryAnnotation> BINARY_ANNOTATION_ADAPTER = new JsonAdapter<BinaryAnnotation>() { @Override public BinaryAnnotation fromJson(JsonReader reader) throws IOException { BinaryAnnotation.Builder result = BinaryAnnotation.builder(); String number = null; String string = null; BinaryAnnotation.Type type = BinaryAnnotation.Type.STRING; reader.beginObject(); while (reader.hasNext()) { switch (reader.nextName()) { case "key": result.key(reader.nextString()); break; case "value": switch (reader.peek()) { case BOOLEAN: type = BinaryAnnotation.Type.BOOL; result.value(reader.nextBoolean() ? new byte[] {1} : new byte[] {0}); break; case STRING: string = reader.nextString(); break; case NUMBER: number = reader.nextString(); break; default: throw new JsonDataException( "Expected value to be a boolean, string or number but was " + reader.peek() + " at path " + reader.getPath()); } break; case "type": type = BinaryAnnotation.Type.valueOf(reader.nextString()); break; case "endpoint": result.endpoint(ENDPOINT_ADAPTER.fromJson(reader)); break; default: reader.skipValue(); } } reader.endObject(); result.type(type); switch (type) { case BOOL: return result.build(); case STRING: return result.value(string.getBytes(UTF_8)).build(); case BYTES: return result.value(ByteString.decodeBase64(string).toByteArray()).build(); default: break; } Buffer buffer = new Buffer(); switch (type) { case I16: buffer.writeShort(Short.parseShort(number)); break; case I32: buffer.writeInt(Integer.parseInt(number)); break; case I64: case DOUBLE: if (number == null) number = string; long v = type == BinaryAnnotation.Type.I64 ? Long.parseLong(number) : Double.doubleToRawLongBits(Double.parseDouble(number)); buffer.writeLong(v); break; default: throw new AssertionError( "BinaryAnnotationType " + type + " was added, but not handled"); } return result.value(buffer.readByteArray()).build(); } @Override public void toJson(JsonWriter writer, BinaryAnnotation value) throws IOException { throw new UnsupportedOperationException(); } }; static final JsonAdapter<DependencyLink> DEPENDENCY_LINK_ADAPTER = new JsonAdapter<DependencyLink>() { @Override public DependencyLink fromJson(JsonReader reader) throws IOException { DependencyLink.Builder result = DependencyLink.builder(); reader.beginObject(); while (reader.hasNext()) { switch (reader.nextName()) { case "parent": result.parent(reader.nextString()); break; case "child": result.child(reader.nextString()); break; case "callCount": result.callCount(reader.nextLong()); break; default: reader.skipValue(); } } reader.endObject(); return result.build(); } @Override public void toJson(JsonWriter writer, DependencyLink value) throws IOException { throw new UnsupportedOperationException(); } }; }
package net.agkn.field_stripe.record.reader; /* * Copyright 2012 Aggregate Knowledge, 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. */ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.io.StringReader; import net.agkn.field_stripe.exception.InvalidDataException; import net.agkn.field_stripe.record.writer.JsonArrayRecordWriterTest; import org.apache.commons.lang.mutable.MutableBoolean; import org.testng.annotations.Test; /** * Unit tests for {@link SmartJsonArrayRecordReader} -- a {@link IRecordReader} * for JSON-array based records. * * @author rgrzywinski * @see JsonArrayRecordWriterTest */ public class SmartJsonArrayRecordReaderTest { /** * Tests multiple records (flat structure for simplicity). */ @Test public void multipleRecordTest() throws Exception { // no record { // locally scoped for sanity final String input = ""/*no record*/; final IRecordReader recordReader = new SmartJsonArrayRecordReader(new StringReader(input)); try { recordReader.startRecord(); assert false : "Expected an exception."; } catch(final InvalidDataException ide) { assertEquals(ide.getLocalizedMessage(), "There are no more records to read."); } } { // locally scoped for sanity final String input = ""/*no record*/; final IRecordReader recordReader = new SmartJsonArrayRecordReader(new StringReader(input)); assertFalse(recordReader.hasMoreRecords(), "No records to read"); assertFalse(recordReader.hasMoreRecords(), "No records to read")/*called again for sanity*/; } // one record with no trailing newline { // locally scoped for sanity final String input = "[1]"; final IRecordReader recordReader = new SmartJsonArrayRecordReader(new StringReader(input)); assertTrue(recordReader.hasMoreRecords(), "There is a record to read"); assertTrue(recordReader.hasMoreRecords(), "There is a record to read")/*called again for sanity*/; final MutableBoolean isSet = new MutableBoolean(); recordReader.startRecord(); assertEquals(recordReader.readIntField(isSet), 1); assertEquals(isSet.booleanValue(), true/*is set*/); recordReader.endRecord(); assertFalse(recordReader.hasMoreRecords(), "No more records to read"); assertFalse(recordReader.hasMoreRecords(), "No more records to read")/*called again for sanity*/; } // one record with trailing newline { // locally scoped for sanity final String input = "[2]\n"/*trailing newline*/; final IRecordReader recordReader = new SmartJsonArrayRecordReader(new StringReader(input)); assertTrue(recordReader.hasMoreRecords(), "There is a record to read"); assertTrue(recordReader.hasMoreRecords(), "There is a record to read")/*called again for sanity*/; final MutableBoolean isSet = new MutableBoolean(); recordReader.startRecord(); assertEquals(recordReader.readIntField(isSet), 2); assertEquals(isSet.booleanValue(), true/*is set*/); recordReader.endRecord(); assertFalse(recordReader.hasMoreRecords(), "No more records to read"); assertFalse(recordReader.hasMoreRecords(), "No more records to read")/*called again for sanity*/; } // multiple records { // locally scoped for sanity // CHECK: is the case "[1]\nnull\n[3]" supported? final String input = "[1]\n" + "[2]\n" + "[3]"; final IRecordReader recordReader = new SmartJsonArrayRecordReader(new StringReader(input)); assertTrue(recordReader.hasMoreRecords(), "There is a record to read"); assertTrue(recordReader.hasMoreRecords(), "There is a record to read")/*called again for sanity*/; final MutableBoolean isSet = new MutableBoolean(); recordReader.startRecord(); assertEquals(recordReader.readIntField(isSet), 1); assertEquals(isSet.booleanValue(), true/*is set*/); recordReader.endRecord(); assertTrue(recordReader.hasMoreRecords(), "There is a record to read"); assertTrue(recordReader.hasMoreRecords(), "There is a record to read")/*called again for sanity*/; recordReader.startRecord(); assertEquals(recordReader.readIntField(isSet), 2); assertEquals(isSet.booleanValue(), true/*is set*/); recordReader.endRecord(); assertTrue(recordReader.hasMoreRecords(), "There is a record to read"); assertTrue(recordReader.hasMoreRecords(), "There is a record to read")/*called again for sanity*/; recordReader.startRecord(); assertEquals(recordReader.readIntField(isSet), 3); assertEquals(isSet.booleanValue(), true/*is set*/); recordReader.endRecord(); assertFalse(recordReader.hasMoreRecords(), "No more records to read"); assertFalse(recordReader.hasMoreRecords(), "No more records to read")/*called again for sanity*/; } } /** * Tests all primitive values in a flat structure. */ @Test public void flatTest() throws Exception { // all values { // locally scoped for sanity final String input = "[1,2,3,4,5.01,6.01,true,\"string\"]"; final IRecordReader recordReader = new SmartJsonArrayRecordReader(new StringReader(input)); final MutableBoolean isSet = new MutableBoolean(); recordReader.startRecord(); assertEquals(recordReader.readByteField(isSet), 1); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readShortField(isSet), 2); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readIntField(isSet), 3); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readLongField(isSet), 4L); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readFloatField(isSet), 5.01f); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readDoubleField(isSet), 6.01); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readBooleanField(isSet), true); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readStringField(isSet), "string"); assertEquals(isSet.booleanValue(), true/*is set*/); recordReader.endRecord(); } // half-null (ensures that isSet is reset each time, etc) { // locally scoped for sanity final String input = "[1,null,3,null,5.01,null,false,null]"; final IRecordReader recordReader = new SmartJsonArrayRecordReader(new StringReader(input)); final MutableBoolean isSet = new MutableBoolean(); recordReader.startRecord(); assertEquals(recordReader.readByteField(isSet), 1); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readShortField(isSet), -1/*any value*/); assertEquals(isSet.booleanValue(), false/*is unset*/); assertEquals(recordReader.readIntField(isSet), 3); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readLongField(isSet), -1L/*any value*/); assertEquals(isSet.booleanValue(), false/*is unset*/); assertEquals(recordReader.readFloatField(isSet), 5.01f); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readDoubleField(isSet), -1.0/*any value*/); assertEquals(isSet.booleanValue(), false/*is unset*/); assertEquals(recordReader.readBooleanField(isSet), false); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readStringField(isSet), ""/*any value*/); assertEquals(isSet.booleanValue(), false/*is unset*/); recordReader.endRecord(); } { // locally scoped for sanity final String input = "[null,2,null,4,null,6.01,null,\"string\"]"; final IRecordReader recordReader = new SmartJsonArrayRecordReader(new StringReader(input)); final MutableBoolean isSet = new MutableBoolean(); recordReader.startRecord(); assertEquals(recordReader.readByteField(isSet), -1/*any value*/); assertEquals(isSet.booleanValue(), false/*is unset*/); assertEquals(recordReader.readShortField(isSet), 2); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readIntField(isSet), -1/*any value*/); assertEquals(isSet.booleanValue(), false/*is unset*/); assertEquals(recordReader.readLongField(isSet), 4L); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readFloatField(isSet), -1.0f/*any value*/); assertEquals(isSet.booleanValue(), false/*is unset*/); assertEquals(recordReader.readDoubleField(isSet), 6.01); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readBooleanField(isSet), false/*any value*/); assertEquals(isSet.booleanValue(), false/*is unset*/); assertEquals(recordReader.readStringField(isSet), "string"); assertEquals(isSet.booleanValue(), true/*is set*/); recordReader.endRecord(); } } /** * Tests all primitive values each in their own array. * * @see JsonArrayRecordWriterTest#arrayTest() */ @Test public void arrayTest() throws Exception { // non-null values { // locally scoped for sanity final String input = "[[111,112],[121,122],[131,132],[141,142],[15.01,15.02],[16.01,16.02],[true,false],[\"string181\",\"string182\"]]"; final IRecordReader recordReader = new SmartJsonArrayRecordReader(new StringReader(input)); final MutableBoolean isSet = new MutableBoolean(); recordReader.startRecord(); assertTrue(recordReader.startArray()); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readByteField(isSet), 111); assertEquals(isSet.booleanValue(), true/*is set*/); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readByteField(isSet), 112); assertEquals(isSet.booleanValue(), true/*is set*/); assertFalse(recordReader.hasMoreElements()); recordReader.endArray(); assertTrue(recordReader.startArray()); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readShortField(isSet), 121); assertEquals(isSet.booleanValue(), true/*is set*/); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readShortField(isSet), 122); assertEquals(isSet.booleanValue(), true/*is set*/); assertFalse(recordReader.hasMoreElements()); recordReader.endArray(); assertTrue(recordReader.startArray()); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readIntField(isSet), 131); assertEquals(isSet.booleanValue(), true/*is set*/); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readIntField(isSet), 132); assertEquals(isSet.booleanValue(), true/*is set*/); assertFalse(recordReader.hasMoreElements()); recordReader.endArray(); assertTrue(recordReader.startArray()); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readLongField(isSet), 141L); assertEquals(isSet.booleanValue(), true/*is set*/); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readLongField(isSet), 142L); assertEquals(isSet.booleanValue(), true/*is set*/); assertFalse(recordReader.hasMoreElements()); recordReader.endArray(); assertTrue(recordReader.startArray()); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readFloatField(isSet), 15.01f); assertEquals(isSet.booleanValue(), true/*is set*/); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readFloatField(isSet), 15.02f); assertEquals(isSet.booleanValue(), true/*is set*/); assertFalse(recordReader.hasMoreElements()); recordReader.endArray(); assertTrue(recordReader.startArray()); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readDoubleField(isSet), 16.01); assertEquals(isSet.booleanValue(), true/*is set*/); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readDoubleField(isSet), 16.02); assertEquals(isSet.booleanValue(), true/*is set*/); assertFalse(recordReader.hasMoreElements()); recordReader.endArray(); assertTrue(recordReader.startArray()); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readBooleanField(isSet), true); assertEquals(isSet.booleanValue(), true/*is set*/); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readBooleanField(isSet), false); assertEquals(isSet.booleanValue(), true/*is set*/); assertFalse(recordReader.hasMoreElements()); recordReader.endArray(); assertTrue(recordReader.startArray()); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readStringField(isSet), "string181"); assertEquals(isSet.booleanValue(), true/*is set*/); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readStringField(isSet), "string182"); assertEquals(isSet.booleanValue(), true/*is set*/); assertFalse(recordReader.hasMoreElements()); recordReader.endArray(); recordReader.endRecord(); } // null arrays and null array values { // locally scoped for sanity final String input = "[null,[],[null]]"; final IRecordReader recordReader = new SmartJsonArrayRecordReader(new StringReader(input)); final MutableBoolean isSet = new MutableBoolean(); recordReader.startRecord(); assertFalse(recordReader.startArray()); assertFalse(recordReader.hasMoreElements()); recordReader.endArray(); assertTrue(recordReader.startArray()); assertFalse(recordReader.hasMoreElements()); recordReader.endArray(); assertTrue(recordReader.startArray()); assertTrue(recordReader.hasMoreElements()); assertEquals(recordReader.readIntField(isSet), -1/*any value*/); assertEquals(isSet.booleanValue(), false/*is unset*/); assertFalse(recordReader.hasMoreElements()); recordReader.endArray(); recordReader.endRecord(); } } /** * Tests all primitive values each in their own structure. * * @see JsonArrayRecordWriterTest#structureTest() */ @Test public void structureTest() throws Exception { { // locally scoped for sanity final String input = "[[111,112,113,114,115.01,116.01,true,\"string118\"]]\n" + "[null]\n"; final IRecordReader recordReader = new SmartJsonArrayRecordReader(new StringReader(input)); final MutableBoolean isSet = new MutableBoolean(); recordReader.startRecord(); assertTrue(recordReader.startStructure()); assertEquals(recordReader.readByteField(isSet), 111); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readShortField(isSet), 112); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readIntField(isSet), 113); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readLongField(isSet), 114L); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readFloatField(isSet), 115.01f); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readDoubleField(isSet), 116.01); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readBooleanField(isSet), true); assertEquals(isSet.booleanValue(), true/*is set*/); assertEquals(recordReader.readStringField(isSet), "string118"); assertEquals(isSet.booleanValue(), true/*is set*/); recordReader.endStructure(); recordReader.endRecord(); assertTrue(recordReader.hasMoreRecords()); recordReader.startRecord(); assertFalse(recordReader.startStructure()); recordReader.endRecord(); assertFalse(recordReader.hasMoreRecords()); } } // TODO: array + structure (and structure + array) tests }
package com.szss; /** * Created by zcg on 16/8/5. */ public class Main { public static void main(String[] args) { akka.Main.main(new String[]{HelloWorldActor.class.getName()}); } }
package com.zhy.adapter.recyclerview.base; import android.support.v4.util.SparseArrayCompat; /** * Created by zhy on 16/6/22. */ public class ItemViewDelegateManager<T> { SparseArrayCompat<ItemViewDelegate<T>> delegates = new SparseArrayCompat(); public int getItemViewDelegateCount() { return delegates.size(); } public ItemViewDelegateManager<T> addDelegate(ItemViewDelegate<T> delegate) { int viewType = delegates.size(); if (delegate != null) { delegates.put(viewType, delegate); viewType++; } return this; } public ItemViewDelegateManager<T> addDelegate(int viewType, ItemViewDelegate<T> delegate) { if (delegates.get(viewType) != null) { throw new IllegalArgumentException( "An ItemViewDelegate is already registered for the viewType = " + viewType + ". Already registered ItemViewDelegate is " + delegates.get(viewType)); } delegates.put(viewType, delegate); return this; } public ItemViewDelegateManager<T> removeDelegate(ItemViewDelegate<T> delegate) { if (delegate == null) { throw new NullPointerException("ItemViewDelegate is null"); } int indexToRemove = delegates.indexOfValue(delegate); if (indexToRemove >= 0) { delegates.removeAt(indexToRemove); } return this; } public ItemViewDelegateManager<T> removeDelegate(int itemType) { int indexToRemove = delegates.indexOfKey(itemType); if (indexToRemove >= 0) { delegates.removeAt(indexToRemove); } return this; } public int getItemViewType(T item, int position) { int delegatesCount = delegates.size(); for (int i = delegatesCount - 1; i >= 0; i--) { ItemViewDelegate<T> delegate = delegates.valueAt(i); if (delegate.isForViewType( item, position)) { return delegates.keyAt(i); } } throw new IllegalArgumentException( "No ItemViewDelegate added that matches position=" + position + " in data source"); } public void convert(ViewHolder holder, T item, int position) { int delegatesCount = delegates.size(); for (int i = 0; i < delegatesCount; i++) { ItemViewDelegate<T> delegate = delegates.valueAt(i); if (delegate.isForViewType( item, position)) { delegate.convert(holder, item, position); return; } } throw new IllegalArgumentException( "No ItemViewDelegateManager added that matches position=" + position + " in data source"); } public ItemViewDelegate getItemViewDelegate(int viewType) { return delegates.get(viewType); } public int getItemViewLayoutId(int viewType) { return getItemViewDelegate(viewType).getItemViewLayoutId(); } public int getItemViewType(ItemViewDelegate itemViewDelegate) { return delegates.indexOfValue(itemViewDelegate); } }
package com.stardust.theme.sample; import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.core.view.GravityCompat; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.widget.Toolbar; import androidx.drawerlayout.widget.DrawerLayout; import android.view.Menu; import android.view.MenuItem; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.navigation.NavigationView; import com.google.android.material.snackbar.Snackbar; import com.stardust.theme.app.ColorSelectActivity; import com.stardust.theme.app.ThemeColorAppCompatActivity; import com.stardust.theme.util.ListBuilder; import java.util.List; public class MainActivity extends ThemeColorAppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private static final List<ColorSelectActivity.ColorItem> colorItems; static { colorItems = new ListBuilder<ColorSelectActivity.ColorItem>() .add(new ColorSelectActivity.ColorItem("基佬红", 0xFFF44336)) .add(new ColorSelectActivity.ColorItem("基佬粉", 0xFFE91E63)) .add(new ColorSelectActivity.ColorItem("基佬紫", 0xFF9C27B0)) .add(new ColorSelectActivity.ColorItem("基深紫", 0xFF673AB7)) .add(new ColorSelectActivity.ColorItem("基靛蓝", 0xFF3F51B5)) .add(new ColorSelectActivity.ColorItem("基佬蓝", 0xFF2196F3)) .add(new ColorSelectActivity.ColorItem("基亮蓝", 0xFF03A9F4)) .add(new ColorSelectActivity.ColorItem("基蓝绿", 0xFF00BCD4)) .add(new ColorSelectActivity.ColorItem("基佬青", 0xFF009688)) .add(new ColorSelectActivity.ColorItem("基佬绿", 0xFF4CAF50)) .add(new ColorSelectActivity.ColorItem("基亮绿", 0xFF8BC34A)) .add(new ColorSelectActivity.ColorItem("基黄绿", 0xFFCDDC39)) .add(new ColorSelectActivity.ColorItem("基佬黄", 0xFFFFEB3B)) .add(new ColorSelectActivity.ColorItem("基琥珀", 0xFFFFC107)) .add(new ColorSelectActivity.ColorItem("基佬橙", 0xFFFF9800)) .add(new ColorSelectActivity.ColorItem("基深橙", 0xFFFF5722)) .add(new ColorSelectActivity.ColorItem("基佬棕", 0xFF795548)) .add(new ColorSelectActivity.ColorItem("基佬灰", 0xFF9E9E9E)) .add(new ColorSelectActivity.ColorItem("基南灰", 0xFF607D8B)) .list(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mt_activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.mt_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { startActivity(new Intent(this, SettingActivity.class)); return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_setting) { startActivity(new Intent(this, SettingActivity.class)); } else if (id == R.id.nav_color_setting) { ColorSelectActivity.startColorSelect(this, "选择颜色", colorItems); } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }