小编Gan*_*aju的帖子

Spring Boot和Nginx集成

在我的项目中,使用Spring引导和默认的tomcat服务器开发Web应用程序.我使用NGINX作为负载均衡器,并在NGINX配置中配置了我的spring-boot-web-app,如下所示:

location /spring-boot-web-app {
     proxy_pass http://spring-boot-web-app/
}

http {
    upstream /spring-boot-web-app {
        server <IP_of_spring_boot_app>:<Port_of_spring_boot_app>
    }
}
Run Code Online (Sandbox Code Playgroud)

现在让我们分别说NGINX IP和端口为nginx_ipnginx_port.我的网络应用程序的工作URL也是:http:// web_app_ip:web_app_port/rest/echo/hi

上面的URL工作正常.但是当我尝试通过NGINX点击相同的URI时,它会抛出404.通过NGINX使用的URL为: http:// nginx_ip:nginx_port/spring-boot-web-app/rest/echo/hi

有什么我想念的吗?

reverse-proxy nginx proxypass docker spring-boot

5
推荐指数
1
解决办法
1万
查看次数

Java将文件编码为Base64字符串以与其他编码字符串匹配

private static String encodeFileToBase64Binary(String fileName)
        throws IOException {

    File file = new File(fileName);
    byte[] bytes = loadFile(file);
    byte[] encoded = Base64.encodeBase64(bytes);
    String encodedString = new String(encoded,StandardCharsets.US_ASCII);

    return encodedString;
}
private static byte[] loadFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

    long length = file.length();
    if (length > Integer.MAX_VALUE) {
        // File is too large
    }
    byte[] bytes = new byte[(int)length];

    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) …
Run Code Online (Sandbox Code Playgroud)

java string base64 encoding utf-8

5
推荐指数
3
解决办法
4万
查看次数

Java通过Gmail发送电子邮件

以下代码应该通过gmail发送电子邮件,但它会出现以下错误:

在此输入图像描述

在我的Gmail帐户上,我收到一条消息,指出登录已被阻止,我应该使用像Gmail这样的安全应用来访问我的帐户.源代码如下所示:

public void doSendMail(){
    username = txtFrom.getText();
    password= new String(txtPassword.getPassword());
    to = txtTo.getText();
    subject = txtSubject.getText();
    email_body = jTextArea1.getText();

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "587");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.port", "587");

    Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator(){
                @Override
                protected PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication(username, password);
                }
    }
    );
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(email_body);
        Transport.send(message);

        JOptionPane.showMessageDialog(this, "Message Sent!","Sent",JOptionPane.INFORMATION_MESSAGE);

    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, e.toString());
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以对代码做什么让它通过gmail发送邮件?

java gmail send

4
推荐指数
1
解决办法
3617
查看次数

spring webflux webclient响应将字符串列表转换为字符串

回复:

[ 
 {
  "version": "1.0",
  "content": [
    "12345",
    "67076",
    "123462",
    "604340",
    "1331999",
    "1332608",
    "1785581",
   ]
 }
]
Run Code Online (Sandbox Code Playgroud)

代码:

Mono<List<String>> mp = webClient.get().uri(accountMgmtURI)
    .retrieve()
    .bodyToMono(Map.class)
    .flatMap(trans-> {
       List<String> content= (List<String>) trans.get("content");
       System.out.println("content :: "+content);
       return Mono.just(content);
     }); 
System.out.println("content :: "+mp.toString()); 
String sites=mp.toString();
Run Code Online (Sandbox Code Playgroud)

mono spring java-8 spring-boot spring-webflux

4
推荐指数
1
解决办法
2万
查看次数

迭代两个列表进行过滤

我有 2 个列表,我正在尝试根据第一个列表中的条件过滤第二个列表。

list1 = [ {'type': 'A', 'name': '1'},{'type': 'B', 'name': '2'},{'type': 'A', 'name': '3'}]
list2 = [100, 200, 300]

filtered_list1 = list(filter(lambda x: (x['type'] == 'A'), list1))
filtered_list2 = list(filter(lambda x: ??????????????????, list2))

# expected output
# filtered_list1 = [ {'type': 'A', 'name': '1'},{'type': 'A', 'name': '3'}]
# filtered_list2 = [100, 300]
Run Code Online (Sandbox Code Playgroud)

我需要根据 list1 中的条件过滤 list2 中的元素。如何迭代两个列表?或者是否可以使用带有过滤器/lambda 的索引?

python list filter

4
推荐指数
1
解决办法
842
查看次数

Spring Boot中如何将特定的短信国际化?

目前我正在实施一项向客户发送通知(例如短信)的服务。服务是用 Java 编写的,基于 Spring Boot。

我想用收件人的语言发送消息。

所以基本上我想要一个方法,用所需的本地化(“en”,“fr”,“es”)获取消息的一些 id 并返回正确的字符串。还配置一些默认语言(如“en”)会很棒 - 如果不支持所需的语言,请回退到它。

任何建议如何使用 Spring Boot 实现这一目标?

PS:对不起,是的,我试过“谷歌搜索”。我找到了几个国际化示例,但其中大多数似乎没有用,因为它们是针对整个用户界面的,而不是针对特定消息的。

java spring internationalization spring-boot

3
推荐指数
1
解决办法
1549
查看次数

在 spring-boot 中从 application.yaml 文件读取 SSH 私钥?

我有一个骆驼应用程序,它使用 SSH 私钥连接到 SFTP 服务器。如果我从文件中读取 id_rsa 文件,我就能够连接到服务器。如本例所示,它正在处理从文件加载。

registry.put("privateKey", getBytesFromFile("./src/main/resources/id_rsa"));

private byte[] getBytesFromFile(String filename) throws IOException {
    InputStream input;
    input = new FileInputStream(new File(filename));
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    IOHelper.copyAndCloseInput(input, output);
    return output.toByteArray();
}
Run Code Online (Sandbox Code Playgroud)

我想在运行时动态提供私钥。这意味着在 spring-boot 应用程序中的 application.yaml 中,它将被 docker 容器环境变量替换。

@Value("${sftp_private_key}")
private String privateKey;

registry.put("privateKey", privateKey.getBytes());
Run Code Online (Sandbox Code Playgroud)

我收到此异常

org.apache.camel.component.file.GenericFileOperationFailedException: Cannot connect to sftp://<user>@<sftp_server>:22
    at org.apache.camel.component.file.remote.SftpOperations.connect(SftpOperations.java:146) ~[camel-ftp-2.19.1.jar:2.19.1]
    at org.apache.camel.component.file.remote.RemoteFileConsumer.connectIfNecessary(RemoteFileConsumer.java:203) [camel-ftp-2.19.1.jar:2.19.1]
    at org.apache.camel.component.file.remote.RemoteFileConsumer.recoverableConnectIfNecessary(RemoteFileConsumer.java:171) [camel-ftp-2.19.1.jar:2.19.1]
    at org.apache.camel.component.file.remote.RemoteFileConsumer.prePollCheck(RemoteFileConsumer.java:59) [camel-ftp-2.19.1.jar:2.19.1]
    at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:110) [camel-core-2.19.1.jar:2.19.1]
    at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:174) [camel-core-2.19.1.jar:2.19.1]
    at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:101) [camel-core-2.19.1.jar:2.19.1]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_121]
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) …
Run Code Online (Sandbox Code Playgroud)

java character-encoding apache-camel spring-boot private-key

3
推荐指数
1
解决办法
8676
查看次数

如何在JavaFX的VBox中移动项目(通过拖动更改顺序)?

我想在VBox中拖动TitledPane。我在VBox中有n个Titlepane。我想在拖动时更改它们的顺序。我尝试了一些MouseEvents和DragEvents。但是它对我不起作用。

但我需要将Titledpane移到哪个位置的索引。基于此,我需要在后端做一些事情。请帮我。

谢谢

javafx event-handling mouseevent vbox

2
推荐指数
1
解决办法
2819
查看次数

DynamoDB查询二级索引,如何定义索引

我一直在四处走动,但不清楚该怎么做。

我有一个简单的表,我想在其中对几列进行查询。据我了解,这意味着为要查询的每一列创建二级索引。我已经使用Serverless框架定义了表,serverless.yml并且收到了各种奇怪的错误消息。

当前的serverless.yml定义是:

resources:
  Resources:
    MessagesDynamoDBTable:
      Type: 'AWS::DynamoDB::Table'
      Properties:
        AttributeDefinitions:
          - AttributeName: messageId
            AttributeType: S
          - AttributeName: room
            AttributeType: S
          - AttributeName: userId
            AttributeType: S
        KeySchema:
          - AttributeName: messageId
            KeyType: HASH
          - AttributeName: userId
            KeyType: RANGE
        LocalSecondaryIndexes:
          - IndexName: roomIndex
            KeySchema: 
              - AttributeName: room
                KeyType: HASH
            Projection: 
              ProjectionType: "KEYS_ONLY"
          - IndexName: userId
            KeySchema: 
              - AttributeName: userId
                KeyType: HASH
            Projection: 
              ProjectionType: "KEYS_ONLY"
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:custom.tableName}
Run Code Online (Sandbox Code Playgroud)

它的意思是类似于Slack服务-因此我想查询房间,用户等的条目。

根据我已经找到的文档,此定义很有意义。一个应该为索引中使用的列声明属性,而我已经这样做了。KeySchema-我确实只需要messageId字段,但是一条错误消息表明它需要RANGE索引,因此我将userId字段添加到KeySchema中只是为了关闭它。根据我已经找到的文档,二级索引字段看起来正确。

有了这个定义,当尝试使用 serverless deploy

An error occurred: …
Run Code Online (Sandbox Code Playgroud)

amazon-dynamodb serverless-framework dynamodb-queries amazon-dynamodb-index

2
推荐指数
1
解决办法
3928
查看次数

如何使用CloudFormation在Redhat中安装aws-cfn-bootstrap / cfn-init软件包?

我正在尝试使用CloudFormation模板启动实例。实例已启动,但UserData部分未完全执行,因为cfn-init/aws-cfn-bootstrapRedhat 7 AMI中未安装软件包。我尝试aws-cfn-bootstrap手动安装软件包,但由于与python版本冲突而无法安装。

这是CloudFormation模板的UserData部分

"UserData": {
                "Fn::Base64": {
                    "Fn::Join": [
                        "\n",
                        [
                            "#!/bin/bash",
                            "set -x",
                            "",
                            "INSTANCE_ID=`/opt/aws/bin/ec2-metadata --instance-id | cut -f2 -d' '`",
                            "REGION=`/opt/aws/bin/ec2-metadata --availability-zone| cut -f2 -d' ' | sed '$s/.$//'`",
                            {
                                "Fn::Join": [
                                    "",
                                    [
                                        "AID='",
                                        {
                                            "Fn::GetAtt": [
                                                "eip",
                                                "AllocationId"
                                            ]
                                        },
                                        "'"
                                    ]
                                ]
                            },
                            "aws ec2 associate-address --region $REGION --instance-id $INSTANCE_ID --allocation-id $AID"
                        ]
                    ]
                }
            }
Run Code Online (Sandbox Code Playgroud)

cloud-init.log

Nov 12 03:55:27 localhost cloud-init: Cloud-init v. 0.7.6 running 'modules:config' at Thu, 12 …
Run Code Online (Sandbox Code Playgroud)

redhat amazon-web-services cloud-init aws-cloudformation

1
推荐指数
2
解决办法
1万
查看次数

Camel 测试 - java.lang.IllegalArgumentException:必须指定 defaultEndpoint

我正在尝试使用http://camel.apache.org/mock.html为我的骆驼路线创建测试用例。我需要验证路由中的处理器。但是简单的测试对我不起作用。

public class CamelRouteTest  extends CamelTestSupport {

  @Override
  public String isMockEndpointsAndSkip() {
    // override this method and return the pattern for which endpoints to mock,
    // and skip sending to the original endpoint.
    return "mock:result";
  }

  @Test
  public void verifyMessageCount() throws Exception {
    template.sendBody("Test");
    getMockEndpoint("mock:result").expectedMessageCount(1);
    assertMockEndpointsSatisfied();
  }

  @Override
  protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").to("mock:result");
        }
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪:

java.lang.IllegalArgumentException: defaultEndpoint must be specified
    at org.apache.camel.util.ObjectHelper.notNull(ObjectHelper.java:308) …
Run Code Online (Sandbox Code Playgroud)

java apache-camel camel-test

1
推荐指数
1
解决办法
5190
查看次数