Explore all Web Services open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Web Services

cloudmapper

2.10.0

GeoIP2-java

3.0.1

onebusaway-android

v2.9.0

node-gtfs

Release 3.2.5

peering-manager

Version 1.6.1 | MARK I

Popular Libraries in Web Services

gmaps

by hpneo doticonjavascriptdoticon

star image 7114 doticon

the easiest way to use Google Maps

cloudmapper

by duo-labs doticonjavascriptdoticon

star image 4813 doticonBSD-3-Clause

CloudMapper helps you analyze your Amazon Web Services (AWS) environments.

js-marker-clusterer

by googlearchive doticonjavascriptdoticon

star image 1286 doticonApache-2.0

A marker clustering library for the Google Maps JavaScript API v3.

ec2-spot-labs

by awslabs doticonjupyter notebookdoticon

star image 797 doticonNOASSERTION

Collection of tools and code examples to demonstrate best practices in using Amazon EC2 Spot Instances.

GeoIP2-java

by maxmind doticonjavadoticon

star image 630 doticonApache-2.0

Java API for GeoIP2 webservice client and database reader

transitfeed

by google doticonpythondoticon

star image 622 doticonApache-2.0

A Python library for reading, validating, and writing transit schedule information in the GTFS format.

freelec-springboot2-webservice

by jojoldu doticonjavadoticon

star image 584 doticon

aws-sa-associate-saac02

by acantril doticonhtmldoticon

star image 499 doticonMIT

Course Files for AWS Certified Solutions Architect Certification Course (SAAC02) - Adrian Cantrill

Polaris

by cyrilmottier doticonjavadoticon

star image 433 doticonApache-2.0

A library greatly enhancing the features of the Google Maps external library: Effortless map annotating, gesture support, map callout support, built-in “user tracking” mode, etc.

Trending New libraries in Web Services

aws-sa-associate-saac02

by acantril doticonhtmldoticon

star image 499 doticonMIT

Course Files for AWS Certified Solutions Architect Certification Course (SAAC02) - Adrian Cantrill

aws-sa-pro

by acantril doticonshelldoticon

star image 286 doticonMIT

Course Files for AWS Certified Solutions Architect - Professional - Adrian Cantrill

OA-tongda-RCE

by jas502n doticonphpdoticon

star image 129 doticon

Office Anywhere网络智能办公系统

energy-data

by owid doticonpythondoticon

star image 79 doticon

Data on energy by Our World in Data

application-migration-with-aws-workshop

by aws-samples doticoncssdoticon

star image 34 doticonNOASSERTION

AWS Application Migration Workshop

maps-platform-101-js

by googlecodelabs doticonjavascriptdoticon

star image 25 doticonApache-2.0

gtfs-via-postgres

by derhuerst doticonjavascriptdoticon

star image 21 doticonNOASSERTION

Yet another tool to process GTFS using PostgreSQL.

fastgtfs

by nicomazz doticonrustdoticon

star image 20 doticonGPL-3.0

A pure Rust library that provides GTFS parsing, navigation, time table creation, and real-time network simulation.

MioGatto

by wtsnjp doticonpythondoticon

star image 20 doticonMIT

An annotation tool for grounding of formulae

Top Authors in Web Services

1

derhuerst

31 Libraries

star icon220

2

OneBusAway

12 Libraries

star icon782

3

transitland

8 Libraries

star icon233

4

aws-samples

7 Libraries

star icon138

5

CUTR-at-USF

6 Libraries

star icon136

6

BlinkTagInc

5 Libraries

star icon575

7

public-transport

5 Libraries

star icon36

8

DeveloperCielo

5 Libraries

star icon84

9

r-transit

5 Libraries

star icon114

10

conveyal

5 Libraries

star icon218

1

31 Libraries

star icon220

2

12 Libraries

star icon782

3

8 Libraries

star icon233

4

7 Libraries

star icon138

5

6 Libraries

star icon136

6

5 Libraries

star icon575

7

5 Libraries

star icon36

8

5 Libraries

star icon84

9

5 Libraries

star icon114

10

5 Libraries

star icon218

Trending Kits in Web Services

No Trending Kits are available at this moment for Web Services

Trending Discussions on Web Services

Deploy AWS Lambda with function URL via Cloudformation

Return multiple possible matches when fuzzy joining two dataframes or vectors in R if they share a word in common

How to create a contact using Business Central API 2.0?

Java integration test with fake outbound call

Problem trying to display custom error pages with Spring Boot

My HTML CSS website is displaying fine on my home computer but terribly on other screen resolutions

How do i set a public URL when using EC2

What will happen if a SSL-configured Nginx reverse proxy pass to an web server without SSL?

RESTful response is not displaying in Chrome after successful test

WebSphere 8 memory leaks

QUESTION

Deploy AWS Lambda with function URL via Cloudformation

Asked 2022-Apr-09 at 08:35

Since a few days, AWS Lambdas can be exposed as web services directly without an API Gateway.

This works fine when setting up through the UI console, but I can’t seem to get it done with Cloudformation, because the resource policy is not attached with AuthType: NONE. And without the policy, I get "message": "Forbidden" from AWS when trying to access the Lambda through the function url.

My Lambda is the following:

1exports.handler = async event => {
2    return {
3        statusCode: 200,
4        body: JSON.stringify("Hello World")
5    }
6}
7

and here’s the CFN template:

1exports.handler = async event => {
2    return {
3        statusCode: 200,
4        body: JSON.stringify("Hello World")
5    }
6}
7AWSTemplateFormatVersion: "2010-09-09"
8
9Parameters:
10  stackName:
11    Type: String
12  lambdaFile:
13    Type: String
14  lambdaBucket:
15    Type: String
16
17Resources:
18  lambdaRole:
19    Type: "AWS::IAM::Role"
20    Properties:
21      AssumeRolePolicyDocument:
22        Version: "2012-10-17"
23        Statement:
24          - Action:
25              - "sts:AssumeRole"
26            Effect: "Allow"
27            Principal:
28              Service:
29                - "lambda.amazonaws.com"
30      Policies:
31        - PolicyDocument:
32            Version: "2012-10-17"
33            Statement:
34              - Action:
35                  - "logs:CreateLogGroup"
36                  - "logs:CreateLogStream"
37                  - "logs:PutLogEvents"
38                Effect: "Allow"
39                Resource:
40                  - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${stackName}:*"
41          PolicyName: "lambda"
42
43  runtimeLambdaFunction:
44    Type: "AWS::Lambda::Function"
45    Properties:
46      Code:
47        S3Bucket: !Ref lambdaBucket
48        S3Key: !Ref lambdaFile
49      Environment:
50        Variables:
51          NODE_ENV: production
52      FunctionName: !Sub "${stackName}-runtime"
53      Handler: runtime.handler
54      MemorySize: 128
55      Role: !GetAtt lambdaRole.Arn
56      Runtime: "nodejs14.x"
57      Timeout: 5
58
59  lambdaLogGroup:
60    Type: "AWS::Logs::LogGroup"
61    Properties:
62      LogGroupName: !Sub "/aws/${stackName}"
63      RetentionInDays: 30
64
65  runtimeLambdaUrl:
66    Type: "AWS::Lambda::Url"
67    Properties:
68      AuthType: NONE
69      TargetFunctionArn: !Ref runtimeLambdaFunction
70
71Outputs:
72  runtimeLambdaUrl:
73    Value: !GetAtt runtimeLambdaUrl.FunctionUrl
74
75

The interesting thing is that I can add the policy through the UI console, and then it works.

Here’s the initial config screen for the function URL right after CFN deployment:

enter image description here

This is what I see when pushing the “Edit” button:

enter image description here

After clicking “Save”, I get the following (note the blue box):

enter image description here

Also, when I go into “Edit” mode again, I now see the following:

enter image description here

After that, the function can be accessed via its URL.

I tried to add the policy into my CFN stack, either standalone as AWS::IAM::Policy, but then it is not a resource-based policy or as an additional action on the lambdaRole. But in either case, I can’t add a Principal and the policy doesn’t have an effect.

Does anybody know how I can make a pure Clouformation deployment for a Lambda with a function URL? Or is this a bug in Cloudformation and/or Lambda?

ANSWER

Answered 2022-Apr-09 at 08:35

Your template is missing AWS::Lambda::Permission, thus its does not work. You already know what the permissions should be based on AWS console inspection, so you have to recreate those permissions using AWS::Lambda::Permission. This allows you to specify FunctionUrlAuthType.

Source https://stackoverflow.com/questions/71806376

QUESTION

Return multiple possible matches when fuzzy joining two dataframes or vectors in R if they share a word in common

Asked 2022-Mar-15 at 18:03

Is there a way of joining two dataframes via where a row in the first dataframe is joined with every row in the second dataframe if they share a word in common?

For example:

1companies1 <- data.frame(company_name = c("Walmart", "Amazon", "Apple", "CVS Health", "UnitedHealth Group", "Berkshire Hathaway", "Alphabet"))
2companies2 <- data.frame(company_name = "Walmart Stores", "Walmart Inc", "Amazon Web Services", "Amazon Alexa", "Apple", "Apple Products", "CVS Health", "UnitedHealth Group", "Berkshire Hathaway", "Berkshire Hathaway Asset Management", "Meta"))
3

I'd like to match these so every single possible match between the left and right column is then returned, as below:

Desired matching output

I've tried packages like fuzzymatch and stringdist, but for matching these seem to return the best match only. However, as the matching I'm doing isn't as neat as the above and is much bigger, my plan is to find possible matches, then give them a distance score (e.g. using Jaro-Winkler distance), at which point I'll have to manually select the right match (if any).

ANSWER

Answered 2022-Mar-15 at 18:03

With fuzzy_join:

1companies1 <- data.frame(company_name = c("Walmart", "Amazon", "Apple", "CVS Health", "UnitedHealth Group", "Berkshire Hathaway", "Alphabet"))
2companies2 <- data.frame(company_name = "Walmart Stores", "Walmart Inc", "Amazon Web Services", "Amazon Alexa", "Apple", "Apple Products", "CVS Health", "UnitedHealth Group", "Berkshire Hathaway", "Berkshire Hathaway Asset Management", "Meta"))
3library(fuzzyjoin)
4fuzzy_join(companies2, companies1, match_fun = stringr::str_detect)
5
6                        company_name.x     company_name.y
71                       Walmart Stores            Walmart
82                          Walmart Inc            Walmart
93                  Amazon Web Services             Amazon
104                         Amazon Alexa             Amazon
115                                Apple              Apple
126                       Apple Products              Apple
137                           CVS Health         CVS Health
148                   UnitedHealth Group UnitedHealth Group
159                   Berkshire Hathaway Berkshire Hathaway
1610 Berkshire Hathaway Asset Management Berkshire Hathaway
17

Or, if you want to respect the order of the columns:

1companies1 <- data.frame(company_name = c("Walmart", "Amazon", "Apple", "CVS Health", "UnitedHealth Group", "Berkshire Hathaway", "Alphabet"))
2companies2 <- data.frame(company_name = "Walmart Stores", "Walmart Inc", "Amazon Web Services", "Amazon Alexa", "Apple", "Apple Products", "CVS Health", "UnitedHealth Group", "Berkshire Hathaway", "Berkshire Hathaway Asset Management", "Meta"))
3library(fuzzyjoin)
4fuzzy_join(companies2, companies1, match_fun = stringr::str_detect)
5
6                        company_name.x     company_name.y
71                       Walmart Stores            Walmart
82                          Walmart Inc            Walmart
93                  Amazon Web Services             Amazon
104                         Amazon Alexa             Amazon
115                                Apple              Apple
126                       Apple Products              Apple
137                           CVS Health         CVS Health
148                   UnitedHealth Group UnitedHealth Group
159                   Berkshire Hathaway Berkshire Hathaway
1610 Berkshire Hathaway Asset Management Berkshire Hathaway
17fuzzy_join(companies1, companies2, match_fun = function(x, y) stringr::str_detect(y, x))
18
19       company_name.x                      company_name.y
201             Walmart                      Walmart Stores
212             Walmart                         Walmart Inc
223              Amazon                 Amazon Web Services
234              Amazon                        Amazon Alexa
245               Apple                               Apple
256               Apple                      Apple Products
267          CVS Health                          CVS Health
278  UnitedHealth Group                  UnitedHealth Group
289  Berkshire Hathaway                  Berkshire Hathaway
2910 Berkshire Hathaway Berkshire Hathaway Asset Management
30
31

Source https://stackoverflow.com/questions/71486862

QUESTION

How to create a contact using Business Central API 2.0?

Asked 2022-Mar-04 at 18:33

(NOTE: The documentation mentioned below is wrong at the time of this submission. It looks like it was copied from a template and not changed. I've submitted comment on Microsoft's GitHub page.)

Has anyone had success creating a contact using the Business Central v2 API? I'm following the documentation here and not having any success. Updates work great, but I can't get create requests working at all.

The documentation says I should be able to post to the contacts end-point like so,

POST businesscentralPrefix/companies({id})/contacts({id})

The fact that {id} is used as a placeholder for both companies and contacts URL components is strange and not at all what I would expect. A more complete example is also given on that page:

1POST https://{businesscentralPrefix}/api/v2.0/companies({id})/contacts({id})
2Content-type: application/json
3{
4    "id" : "5d115c9c-44e3-ea11-bb43-000d3a2feca1",
5    "number" : "108001",
6    "type" : "Company",
7    "displayName": "CRONUS USA, Inc.",
8    "companyNumber" : "17806",
9    "companyName" : "CRONUS US",
10    "businessRelation" : "Vendor",
11    "addressLine1": "7122 South Ashford Street",
12    "addressLine2": "Westminster",
13    "city": "Atlanta",
14    "state": "GA",
15    "country": "US",
16    "postalCode": "31772",
17    "phoneNumber": "+1 425 555 0100",
18    "mobilePhoneNumber" : "",
19    "email" : "ah@contoso.com",
20    "website" : "",
21    "searchName" : "",
22    "privacyBlocked" : true,
23    "lastInteractionDate" : "2021-06-01",
24    "lastModifiedDateTime" : "2021-06-01"
25}
26

The example has an id property in the payload, which doesn't seem like something I should be creating. Again the id here is confusing given the duplicate {id} placeholders in the URL.

Additionally, there are some header requirements that don't make sense for a create request:

If-Match Required. When this request header is included and the eTag provided does not match the current tag on the contact, the contact will not be updated.

I won't have an etag if I'm creating a contact, so that header doesn't seem to apply to create requests. If that's the case, then probably can't rely much on the documentation. If that's the case, then I can't help but wonder if the create end-point shouldn't be:

POST https://{businesscentralPrefix}/api/v2.0/companies({company-guid})/contacts

which seems more consistent with other REST APIs I've encountered, but leaves me wondering whether or not I need supply the id for the new contact? I'm going with "no", but Microsoft's documentation doesn't mention it outside of the examples.

I have no problems updating an existing contact. I'm left with three options for creating one:

  1. POST https://{businesscentralPrefix}/api/v2.0/companies({company-guid})/contacts({company-guid})

    This one is what the docs imply, but it doesn't make any sense given that you're effectively filtering the contacts table by a company id. I gave it a shot just for the sake of it

1POST https://{businesscentralPrefix}/api/v2.0/companies({id})/contacts({id})
2Content-type: application/json
3{
4    "id" : "5d115c9c-44e3-ea11-bb43-000d3a2feca1",
5    "number" : "108001",
6    "type" : "Company",
7    "displayName": "CRONUS USA, Inc.",
8    "companyNumber" : "17806",
9    "companyName" : "CRONUS US",
10    "businessRelation" : "Vendor",
11    "addressLine1": "7122 South Ashford Street",
12    "addressLine2": "Westminster",
13    "city": "Atlanta",
14    "state": "GA",
15    "country": "US",
16    "postalCode": "31772",
17    "phoneNumber": "+1 425 555 0100",
18    "mobilePhoneNumber" : "",
19    "email" : "ah@contoso.com",
20    "website" : "",
21    "searchName" : "",
22    "privacyBlocked" : true,
23    "lastInteractionDate" : "2021-06-01",
24    "lastModifiedDateTime" : "2021-06-01"
25}
26POST https://{businesscentralPrefix}/api/v2.0/companies({company-guid})/contacts({company-guid})
27{
28    "id":"8adc4ec5-8393-44ac-8860-fadd9e3603cb",
29    "number": "TEST123",
30    "displayName": "Another Test Contact",
31    "type": "Person",
32    ...
33}
34...
35Response (with and without the contact guid in payload)
36{
37    "error": {
38        "code": "BadRequest_MethodNotAllowed",
39        "message": "'POST' requests for 'contacts' of EdmType 'Entity' are not allowed within Dynamics 365 Business Central OData web services.  CorrelationId:  XXX"
40    }
41}
42
  1. POST https://{businesscentralPrefix}/api/v2.0/companies({company-guid})/contacts({contact-guid})

    this one also seems weird since it doesn't seem like I should be creating the record's id. Also tried it just to try it:

1POST https://{businesscentralPrefix}/api/v2.0/companies({id})/contacts({id})
2Content-type: application/json
3{
4    "id" : "5d115c9c-44e3-ea11-bb43-000d3a2feca1",
5    "number" : "108001",
6    "type" : "Company",
7    "displayName": "CRONUS USA, Inc.",
8    "companyNumber" : "17806",
9    "companyName" : "CRONUS US",
10    "businessRelation" : "Vendor",
11    "addressLine1": "7122 South Ashford Street",
12    "addressLine2": "Westminster",
13    "city": "Atlanta",
14    "state": "GA",
15    "country": "US",
16    "postalCode": "31772",
17    "phoneNumber": "+1 425 555 0100",
18    "mobilePhoneNumber" : "",
19    "email" : "ah@contoso.com",
20    "website" : "",
21    "searchName" : "",
22    "privacyBlocked" : true,
23    "lastInteractionDate" : "2021-06-01",
24    "lastModifiedDateTime" : "2021-06-01"
25}
26POST https://{businesscentralPrefix}/api/v2.0/companies({company-guid})/contacts({company-guid})
27{
28    "id":"8adc4ec5-8393-44ac-8860-fadd9e3603cb",
29    "number": "TEST123",
30    "displayName": "Another Test Contact",
31    "type": "Person",
32    ...
33}
34...
35Response (with and without the contact guid in payload)
36{
37    "error": {
38        "code": "BadRequest_MethodNotAllowed",
39        "message": "'POST' requests for 'contacts' of EdmType 'Entity' are not allowed within Dynamics 365 Business Central OData web services.  CorrelationId:  XXX"
40    }
41}
42POST https://api.businesscentral.dynamics.com/v2.0/{tenent-guid}/{environment}/api/v2.0/companies({company-guid})/contacts(8adc4ec5-8393-44ac-8860-fadd9e3603cb)
43{
44    "id":"8adc4ec5-8393-44ac-8860-fadd9e3603cb",
45    "number": "TEST123",
46    "displayName": "Another Test Contact",
47    "type": "Person",
48    ...
49}
50...
51Response (with and without the contact id guid in payload)
52{
53    "error": {
54        "code": "BadRequest_MethodNotAllowed",
55        "message": "'POST' requests for 'contacts' of EdmType 'Entity' are not allowed within Dynamics 365 Business Central OData web services.  CorrelationId:  XXXX."
56    }
57}
58
  1. POST https://{businesscentralPrefix}/api/v2.0/companies({company-guid})/contacts

    Number 3 makes sense in my mind but fails with

1POST https://{businesscentralPrefix}/api/v2.0/companies({id})/contacts({id})
2Content-type: application/json
3{
4    "id" : "5d115c9c-44e3-ea11-bb43-000d3a2feca1",
5    "number" : "108001",
6    "type" : "Company",
7    "displayName": "CRONUS USA, Inc.",
8    "companyNumber" : "17806",
9    "companyName" : "CRONUS US",
10    "businessRelation" : "Vendor",
11    "addressLine1": "7122 South Ashford Street",
12    "addressLine2": "Westminster",
13    "city": "Atlanta",
14    "state": "GA",
15    "country": "US",
16    "postalCode": "31772",
17    "phoneNumber": "+1 425 555 0100",
18    "mobilePhoneNumber" : "",
19    "email" : "ah@contoso.com",
20    "website" : "",
21    "searchName" : "",
22    "privacyBlocked" : true,
23    "lastInteractionDate" : "2021-06-01",
24    "lastModifiedDateTime" : "2021-06-01"
25}
26POST https://{businesscentralPrefix}/api/v2.0/companies({company-guid})/contacts({company-guid})
27{
28    "id":"8adc4ec5-8393-44ac-8860-fadd9e3603cb",
29    "number": "TEST123",
30    "displayName": "Another Test Contact",
31    "type": "Person",
32    ...
33}
34...
35Response (with and without the contact guid in payload)
36{
37    "error": {
38        "code": "BadRequest_MethodNotAllowed",
39        "message": "'POST' requests for 'contacts' of EdmType 'Entity' are not allowed within Dynamics 365 Business Central OData web services.  CorrelationId:  XXX"
40    }
41}
42POST https://api.businesscentral.dynamics.com/v2.0/{tenent-guid}/{environment}/api/v2.0/companies({company-guid})/contacts(8adc4ec5-8393-44ac-8860-fadd9e3603cb)
43{
44    "id":"8adc4ec5-8393-44ac-8860-fadd9e3603cb",
45    "number": "TEST123",
46    "displayName": "Another Test Contact",
47    "type": "Person",
48    ...
49}
50...
51Response (with and without the contact id guid in payload)
52{
53    "error": {
54        "code": "BadRequest_MethodNotAllowed",
55        "message": "'POST' requests for 'contacts' of EdmType 'Entity' are not allowed within Dynamics 365 Business Central OData web services.  CorrelationId:  XXXX."
56    }
57}
58POST https://api.businesscentral.dynamics.com/v2.0/{tenent-guid}/{environment}/api/v2.0/companies({company-guid})/contacts(8adc4ec5-8393-44ac-8860-fadd9e3603cb)
59
60{
61    "id":"8adc4ec5-8393-44ac-8860-fadd9e3603cb",
62    "number": "TEST123",
63    "displayName": "Another Test Contact",
64    "type": "Person",
65    ...
66}
67...
68Response (with and without the contact id guid in payload)
69{
70    "error": {
71        "code": "Internal_RecordNotFound",
72        "message": "The Contact does not exist. Identification fields and values: No.='TEST123'  CorrelationId:  XXX."
73    }
74}
75

Has anyone had success creating a contact using the Business Central v2 API? If so, how did you do it and what am I doing wrong? Also, the system I'm working with was upgrade from a local NAV instance, fwiw.

ANSWER

Answered 2022-Mar-04 at 09:56

The error seems to occur when both number and type is included in the payload.

The solution would be to create the contact without either number or type and then update the value you left out with a patch request.

Source https://stackoverflow.com/questions/71345708

QUESTION

Java integration test with fake outbound call

Asked 2022-Jan-24 at 19:45

I work on a Java project using Spring framework, JUnit and Mockito.

The application is in the middle of a chain with others application, so it exposes inbound ports (e.g. an HTTP API) to be called and uses outbound ports (e.g. web services and database) to call other apps.

I want to write something like an integration test that should pass through the whole java code from the inbound port to the outbound port, but without doing any call to anything that's outside of the project.

Let's take a very-simple-but-very-concrete example :

class diagram

We expose an HTTP endpoint to get customers and we call another app to get them.

  • In the domain : customers are represented by the Customer class.
  • In the externalapp layer : customers are represented by the CustomerModel class.
  • In the rest layer : customers are represented by the CustomerDto class.

Thus :

  • The CustomerSupplierAdapter class gets data from CustomerRepository and does the mapping from CustomerModel to Customer.
  • The CustomerControllerAdapter class does the mapping from Customer to CustomerDto and returns the data.

Now, I want to test my app by calling the CustomerControllerAdapter's getCustomers(), which will call the real service, which will call the real supplier, which will call a fake repository.

I wrote the following code :

1@ExtendWith(SpringExtension.class)
2class CustomerIntegrationTest {
3
4    @Mock
5    private CustomerRepository repository;
6
7    @InjectMocks
8    private CustomerControllerAdapter controller;
9
10    @BeforeAll
11    void setupAll() {
12        CustomerOutboundPort customerOutboundPort = new CustomerSupplierAdapter(repository);
13        CustomerInboundPort customerInboundPort = new CustomerService(customerOutboundPort);
14        controller = new CustomerControllerAdapter(customerInboundPort);
15    }
16
17    @Test
18    void bulkQuery() {
19        // Given
20        CustomerModel model = new CustomerModel();
21        model.setName("Arya Stark");
22        doReturn(List.of(model)).when(repository).getCustomers();
23
24        // When
25        List<CustomerDto> dtos = controller.getCustomers();
26
27        // Then
28        assertThat(dtos).hasSize(1);
29        assertThat(dtos.get(0).getName()).isEqualTo("Arya Stark");
30    }
31    
32}
33

But in this code, I do the "constructor's wiring" by myself in the setupAll() instead of relying on Spring dependency injection. It is not a viable solution because it would be very hard to maintain in real-life context (controller may have multiple services, service may have multiple suppliers, etc).

Actually, I would like to have something like an annotation to set on a CustomerRepository instance to programmatically overload dependency injection. Like : "Hey Spring, if any @Service class needs a CustomerRepository then you should use this fake one instead of the usual concrete implementation" without having to do the wiring by myself.

Is there any way to achieve that using Spring, JUnit, Mockito or anything else ?

ANSWER

Answered 2022-Jan-24 at 19:45

If you really want to replace every CustomerRepository in your tests (everywhere!) with a mock, I'd recommend going for a configuration which provides a @Bean, which creates a mocked bean.

1@ExtendWith(SpringExtension.class)
2class CustomerIntegrationTest {
3
4    @Mock
5    private CustomerRepository repository;
6
7    @InjectMocks
8    private CustomerControllerAdapter controller;
9
10    @BeforeAll
11    void setupAll() {
12        CustomerOutboundPort customerOutboundPort = new CustomerSupplierAdapter(repository);
13        CustomerInboundPort customerInboundPort = new CustomerService(customerOutboundPort);
14        controller = new CustomerControllerAdapter(customerInboundPort);
15    }
16
17    @Test
18    void bulkQuery() {
19        // Given
20        CustomerModel model = new CustomerModel();
21        model.setName("Arya Stark");
22        doReturn(List.of(model)).when(repository).getCustomers();
23
24        // When
25        List<CustomerDto> dtos = controller.getCustomers();
26
27        // Then
28        assertThat(dtos).hasSize(1);
29        assertThat(dtos.get(0).getName()).isEqualTo("Arya Stark");
30    }
31    
32}
33@Profile("test")
34@Configuration
35public class TestConfiguration {
36    @Bean
37    @Primary
38    public CustomerRepository customerRepostiory() {
39        return Mockito.mock(CustomerRepository.class);
40    }
41}
42

@MockBean can have negative effects on your test duration as it's quite possible Spring needs to restart it's context.

Alternatively, I'd recommend NOT mocking your repository at all, but instead using either an in memory equivalent (H2) or the TestContainers framework to start the real database for you. Instead of mocking, you insert data into your repository before you start your tests.

Source https://stackoverflow.com/questions/70837026

QUESTION

Problem trying to display custom error pages with Spring Boot

Asked 2022-Jan-21 at 12:54

I'm maintaining a Spring Boot Application that uses Swagger to define Rest web services and uses Maven for dependency management. It uses an application.yml file for properties. By default, when an error occurs, a Whitelabel page is displayed in any browser.

The parent in the application's pom.xml is defined as follows:

1<parent>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-parent</artifactId>
4    <version>2.1.1.RELEASE</version>
5    <relativePath /> <!-- lookup parent from repository -->
6</parent>
7
8

I created HTML pages in the resources/templates/error and resources/public/error each for a generic error, a 404 error, a 401 error and a 500 error.

Afterwards, I tried the following solutions without success:

  1. According to https://www.baeldung.com/spring-boot-custom-error-page, I must follow these steps:

1.1. Disable the Whitelabel display from the properties file or from the main class. I have chosen to do it from the main class:

1<parent>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-parent</artifactId>
4    <version>2.1.1.RELEASE</version>
5    <relativePath /> <!-- lookup parent from repository -->
6</parent>
7
8@SpringBootApplication(scanBasePackages = "com.mycompanyname")
9@EnableConfigurationProperties(AppProperties.class)
10@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class}) // <- Like this!
11public class BuySellBackendApplication {
12
13    public static void main(String[] args) {
14        SpringApplication.run(BuySellBackendApplication.class, args);
15    }
16}
17

1.2. Define a custom error controller that implements the ÈrrorController interface. Mine is defined as follows:

1<parent>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-parent</artifactId>
4    <version>2.1.1.RELEASE</version>
5    <relativePath /> <!-- lookup parent from repository -->
6</parent>
7
8@SpringBootApplication(scanBasePackages = "com.mycompanyname")
9@EnableConfigurationProperties(AppProperties.class)
10@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class}) // <- Like this!
11public class BuySellBackendApplication {
12
13    public static void main(String[] args) {
14        SpringApplication.run(BuySellBackendApplication.class, args);
15    }
16}
17@Controller
18public class BazaarErrorController implements ErrorController {
19
20    @Override
21    public String getErrorPath() {
22        return "/custom-error";
23    }
24
25    @RequestMapping("/custom-error")
26    public String handleError() {
27        return "error";
28    }
29}
30

1.3. Add the path to the error mapping defined from the properties file. As I am using a yml file, the property is added as follows:

1<parent>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-parent</artifactId>
4    <version>2.1.1.RELEASE</version>
5    <relativePath /> <!-- lookup parent from repository -->
6</parent>
7
8@SpringBootApplication(scanBasePackages = "com.mycompanyname")
9@EnableConfigurationProperties(AppProperties.class)
10@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class}) // <- Like this!
11public class BuySellBackendApplication {
12
13    public static void main(String[] args) {
14        SpringApplication.run(BuySellBackendApplication.class, args);
15    }
16}
17@Controller
18public class BazaarErrorController implements ErrorController {
19
20    @Override
21    public String getErrorPath() {
22        return "/custom-error";
23    }
24
25    @RequestMapping("/custom-error")
26    public String handleError() {
27        return "error";
28    }
29}
30server:
31   error:
32      path: "/custom-error"
33

The desired result is to display the generic error page I defined. However, the obtained result is an error page defined by Tomcat. Moreover, Tomcat's error page is triggered from the following class in the application, that uses Spring Security:

1<parent>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-parent</artifactId>
4    <version>2.1.1.RELEASE</version>
5    <relativePath /> <!-- lookup parent from repository -->
6</parent>
7
8@SpringBootApplication(scanBasePackages = "com.mycompanyname")
9@EnableConfigurationProperties(AppProperties.class)
10@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class}) // <- Like this!
11public class BuySellBackendApplication {
12
13    public static void main(String[] args) {
14        SpringApplication.run(BuySellBackendApplication.class, args);
15    }
16}
17@Controller
18public class BazaarErrorController implements ErrorController {
19
20    @Override
21    public String getErrorPath() {
22        return "/custom-error";
23    }
24
25    @RequestMapping("/custom-error")
26    public String handleError() {
27        return "error";
28    }
29}
30server:
31   error:
32      path: "/custom-error"
33public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
34
35    private static final Logger logger = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class);
36
37    @Override
38    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
39        logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
40        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getLocalizedMessage());  // <- This line of code
41    }
42}
43

In those circumstances, even using the @RequestBody annotation and/or make return a different page according to the obtained HTTP error code is useless.

I cannot erase the lines of code of the authentication entry point due to the company's requirements. Also, instead of redirecting me to my error page, it opens the browser's download dialog.

  1. According to https://www.logicbig.com/tutorials/spring-framework/spring-boot/servlet-error-handling-outside-mvc.html, I must define an error page register. Spring Web provides the ErrorPageRegistrar interface to do this:
1<parent>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-parent</artifactId>
4    <version>2.1.1.RELEASE</version>
5    <relativePath /> <!-- lookup parent from repository -->
6</parent>
7
8@SpringBootApplication(scanBasePackages = "com.mycompanyname")
9@EnableConfigurationProperties(AppProperties.class)
10@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class}) // <- Like this!
11public class BuySellBackendApplication {
12
13    public static void main(String[] args) {
14        SpringApplication.run(BuySellBackendApplication.class, args);
15    }
16}
17@Controller
18public class BazaarErrorController implements ErrorController {
19
20    @Override
21    public String getErrorPath() {
22        return "/custom-error";
23    }
24
25    @RequestMapping("/custom-error")
26    public String handleError() {
27        return "error";
28    }
29}
30server:
31   error:
32      path: "/custom-error"
33public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
34
35    private static final Logger logger = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class);
36
37    @Override
38    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
39        logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
40        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getLocalizedMessage());  // <- This line of code
41    }
42}
43@Bean
44public ErrorPageRegistrar errorPageRegistrar() {
45    return registry -> {
46        ErrorPage e404=new ErrorPage(HttpStatus.NOT_FOUND, "/error/" + HttpStatus.NOT_FOUND.value());
47        ErrorPage e401=new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/" + HttpStatus.UNAUTHORIZED.value());
48        ErrorPage e500=new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/" + HttpStatus.INTERNAL_SERVER_ERROR.value());
49        ErrorPage egeneric=new ErrorPage("/error/error");
50        registry.addErrorPages(e401, e404, e500, egeneric);
51    };
52}
53

The obtained result is the same as overriding the Authentication entry point and go to the browser's download dialog in solution 1. Also, it's not very clear if the String argument in the ErrorPage's constructor is a physical HTML file or a servlet mapping.

  1. Define an error view resolver using Spring's ErrorViewResolver interface as described in https://forketyfork.medium.com/how-to-customize-error-page-selection-logic-in-spring-boot-8ea1a6ae122d:
1<parent>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-parent</artifactId>
4    <version>2.1.1.RELEASE</version>
5    <relativePath /> <!-- lookup parent from repository -->
6</parent>
7
8@SpringBootApplication(scanBasePackages = "com.mycompanyname")
9@EnableConfigurationProperties(AppProperties.class)
10@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class}) // <- Like this!
11public class BuySellBackendApplication {
12
13    public static void main(String[] args) {
14        SpringApplication.run(BuySellBackendApplication.class, args);
15    }
16}
17@Controller
18public class BazaarErrorController implements ErrorController {
19
20    @Override
21    public String getErrorPath() {
22        return "/custom-error";
23    }
24
25    @RequestMapping("/custom-error")
26    public String handleError() {
27        return "error";
28    }
29}
30server:
31   error:
32      path: "/custom-error"
33public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
34
35    private static final Logger logger = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class);
36
37    @Override
38    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
39        logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
40        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getLocalizedMessage());  // <- This line of code
41    }
42}
43@Bean
44public ErrorPageRegistrar errorPageRegistrar() {
45    return registry -> {
46        ErrorPage e404=new ErrorPage(HttpStatus.NOT_FOUND, "/error/" + HttpStatus.NOT_FOUND.value());
47        ErrorPage e401=new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/" + HttpStatus.UNAUTHORIZED.value());
48        ErrorPage e500=new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/" + HttpStatus.INTERNAL_SERVER_ERROR.value());
49        ErrorPage egeneric=new ErrorPage("/error/error");
50        registry.addErrorPages(e401, e404, e500, egeneric);
51    };
52}
53@Configuration
54public class ErrorPageConfig {
55    private static final Logger logger = LoggerFactory.getLogger(ErrorPageConfig.class);
56    @Bean
57    public ErrorViewResolver errorViewResolver(ApplicationContext context, ResourceProperties properties){
58        ErrorViewResolver resolver=(request, status, model) -> {
59            String pathFormat="error/%d";
60            String path="";
61            switch(status.value()) {
62                case 401: case 404: case 500:
63                    path=String.format(pathFormat, status.value());
64                    break;
65                default:
66                    logger.info("Codigo de error obtenido {}", status.value());
67                    path="error/error";
68                    break;
69            }
70            return new ModelAndView(path);
71        };
72        return resolver;
73    }
74}
75

It gives me the same result as solution 2.

How can I resolve this problem? Thanks in advance

ANSWER

Answered 2022-Jan-21 at 12:54

SOLVED

The solution is as follows:

  1. Do not disable the Whitelabel display from the properties file or from the main class.

  2. Define the error view resolver completely as in solution 3.

  3. The HTML pages must be in resources/templates

  4. You must add the following dependency to your application's pom.xml

1<parent>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-parent</artifactId>
4    <version>2.1.1.RELEASE</version>
5    <relativePath /> <!-- lookup parent from repository -->
6</parent>
7
8@SpringBootApplication(scanBasePackages = "com.mycompanyname")
9@EnableConfigurationProperties(AppProperties.class)
10@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class}) // <- Like this!
11public class BuySellBackendApplication {
12
13    public static void main(String[] args) {
14        SpringApplication.run(BuySellBackendApplication.class, args);
15    }
16}
17@Controller
18public class BazaarErrorController implements ErrorController {
19
20    @Override
21    public String getErrorPath() {
22        return "/custom-error";
23    }
24
25    @RequestMapping("/custom-error")
26    public String handleError() {
27        return "error";
28    }
29}
30server:
31   error:
32      path: "/custom-error"
33public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
34
35    private static final Logger logger = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class);
36
37    @Override
38    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
39        logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
40        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getLocalizedMessage());  // <- This line of code
41    }
42}
43@Bean
44public ErrorPageRegistrar errorPageRegistrar() {
45    return registry -> {
46        ErrorPage e404=new ErrorPage(HttpStatus.NOT_FOUND, "/error/" + HttpStatus.NOT_FOUND.value());
47        ErrorPage e401=new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/" + HttpStatus.UNAUTHORIZED.value());
48        ErrorPage e500=new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/" + HttpStatus.INTERNAL_SERVER_ERROR.value());
49        ErrorPage egeneric=new ErrorPage("/error/error");
50        registry.addErrorPages(e401, e404, e500, egeneric);
51    };
52}
53@Configuration
54public class ErrorPageConfig {
55    private static final Logger logger = LoggerFactory.getLogger(ErrorPageConfig.class);
56    @Bean
57    public ErrorViewResolver errorViewResolver(ApplicationContext context, ResourceProperties properties){
58        ErrorViewResolver resolver=(request, status, model) -> {
59            String pathFormat="error/%d";
60            String path="";
61            switch(status.value()) {
62                case 401: case 404: case 500:
63                    path=String.format(pathFormat, status.value());
64                    break;
65                default:
66                    logger.info("Codigo de error obtenido {}", status.value());
67                    path="error/error";
68                    break;
69            }
70            return new ModelAndView(path);
71        };
72        return resolver;
73    }
74}
75<dependency>
76    <groupId>org.springframework.boot</groupId>
77    <artifactId>spring-boot-starter-thymeleaf</artifactId>
78</dependency>
79

I hope this helps for everybody who needs it.

Source https://stackoverflow.com/questions/69724950

QUESTION

My HTML CSS website is displaying fine on my home computer but terribly on other screen resolutions

Asked 2022-Jan-05 at 17:53

as the title states,

I am having trouble displaying my webpage properly on other screen resolutions.

I am not certain why it looks so bad on other screen resolutions and not scaling to the device itself.

I don't know exactly where to start, I would think that it has something to do with the way that I positioned my div containers but I am not too sure...

and would like a more experienced person to answer my question before I started messing with the code.

below is my HTML, CSS code:

1body {
2  margin: 0px 140px 0px 140px;
3  font-family: Rockwell;
4}
5
6#left_border {
7  position: relative;
8  height: 100%;
9  border-left: 70px solid orange;
10  padding-left: 50px;
11}
12
13#right_border {
14  position: relative;
15  height: 220%;
16  border-right: 70px solid orange;
17  padding-right: 50px;
18}
19
20#header {
21  background-color: Black;
22  padding-bottom: 6%;
23}
24
25h1 {
26  color: orange;
27  font-size: 30px;
28  font-family: Rockwell;
29  position: absolute;
30  left: 45%;
31}
32
33h2 {
34  color: white;
35  text-align: center;
36}
37
38h3 {
39  font-weight: bold;
40  color: orange;
41  text-align: center;
42}
43
44#positioning_a {
45  position: absolute;
46  left: 65%;
47  top: 3.5%;
48  color: orange;
49  font-size: 21px;
50  font-family: Rockwell;
51}
52
53#positioning_b {
54  position: absolute;
55  left: 70.5%;
56  top: 3.5%;
57  font-size: 21px;
58  font-family: Rockwell;
59}
60
61#positioning_c {
62  position: absolute;
63  top: 3.1%;
64  left: 15.5%;
65  color: orange;
66  font-size: 21px;
67  font-family: Rockwell;
68}
69
70#positioning_d {
71  position: absolute;
72  top: 3.3%;
73  left: 29.5%;
74  font-size: 21px;
75  font-family: Rockwell;
76}
77
78a[href^="mailto:"] {
79  color: white;
80  text-decoration: none;
81}
82
83img {
84  position: relative;
85  width: 110px;
86  height: auto;
87  left: 90%;
88  margin-top: 30px;
89}
90
91footer {
92  background-color: Black;
93  padding-bottom: 70px;
94  margin-top: 50px;
95  margin-top: 60px;
96}
97
98.Right_Side {
99  margin-left: 80%;
100}
101
102.Upwards {
103  position: relative;
104  bottom: 20px;
105}
106
107.pretty {
108  background-color: #0e76a8;
109  color: White;
110  padding: 20px 20px 20px 20px;
111  text-align: center;
112  position: relative;
113  left: 42.5%;
114  top: 25px;
115  text-decoration: none;
116}
117
118#footer {
119  background-color: Black;
120  padding-bottom: 70px;
121  border: 1px solid black;
122}
123
124.weight {
125  font-weight: bold;
126}
127
128.Counter {
129  position: relative;
130  top: 60px;
131  left: 25px;
132  color: white;
133}
1body {
2  margin: 0px 140px 0px 140px;
3  font-family: Rockwell;
4}
5
6#left_border {
7  position: relative;
8  height: 100%;
9  border-left: 70px solid orange;
10  padding-left: 50px;
11}
12
13#right_border {
14  position: relative;
15  height: 220%;
16  border-right: 70px solid orange;
17  padding-right: 50px;
18}
19
20#header {
21  background-color: Black;
22  padding-bottom: 6%;
23}
24
25h1 {
26  color: orange;
27  font-size: 30px;
28  font-family: Rockwell;
29  position: absolute;
30  left: 45%;
31}
32
33h2 {
34  color: white;
35  text-align: center;
36}
37
38h3 {
39  font-weight: bold;
40  color: orange;
41  text-align: center;
42}
43
44#positioning_a {
45  position: absolute;
46  left: 65%;
47  top: 3.5%;
48  color: orange;
49  font-size: 21px;
50  font-family: Rockwell;
51}
52
53#positioning_b {
54  position: absolute;
55  left: 70.5%;
56  top: 3.5%;
57  font-size: 21px;
58  font-family: Rockwell;
59}
60
61#positioning_c {
62  position: absolute;
63  top: 3.1%;
64  left: 15.5%;
65  color: orange;
66  font-size: 21px;
67  font-family: Rockwell;
68}
69
70#positioning_d {
71  position: absolute;
72  top: 3.3%;
73  left: 29.5%;
74  font-size: 21px;
75  font-family: Rockwell;
76}
77
78a[href^="mailto:"] {
79  color: white;
80  text-decoration: none;
81}
82
83img {
84  position: relative;
85  width: 110px;
86  height: auto;
87  left: 90%;
88  margin-top: 30px;
89}
90
91footer {
92  background-color: Black;
93  padding-bottom: 70px;
94  margin-top: 50px;
95  margin-top: 60px;
96}
97
98.Right_Side {
99  margin-left: 80%;
100}
101
102.Upwards {
103  position: relative;
104  bottom: 20px;
105}
106
107.pretty {
108  background-color: #0e76a8;
109  color: White;
110  padding: 20px 20px 20px 20px;
111  text-align: center;
112  position: relative;
113  left: 42.5%;
114  top: 25px;
115  text-decoration: none;
116}
117
118#footer {
119  background-color: Black;
120  padding-bottom: 70px;
121  border: 1px solid black;
122}
123
124.weight {
125  font-weight: bold;
126}
127
128.Counter {
129  position: relative;
130  top: 60px;
131  left: 25px;
132  color: white;
133}<!DOCTYPE.html>
134<html dir="ltr" lang="en-US">
135
136<head>
137  <script src="myScript.js"></script>
138  <title> Online Resume </title>
139  <link rel="stylesheet" type="text/css" href="style.css">
140</head>
141
142<body>
143  <div class="container">
144    <header id="header">
145      <h1> Noah Harris </h1>
146      <h2>
147        <div id="positioning_a"> Email: </div>
148        <div id="positioning_b"> <a href="mailto:harrisspeed@gmail.com"> harrisspeed@gmail.com </a> </div>
149        <div id="positioning_c"> Phone Number: </div>
150        <div id="positioning_d"> 703-400-5998 </div>
151      </h2>
152  </div>
153  </header>
154  <div id="right_border">
155    <div id="left_border">
156      <img src="Badge.jpg" alt="Badge">
157      <h3> About Me </h3>
158      <p> Hello readers My name is Noah and I am partaking in the Cloud Resume Challenge <a href="https://cloudresumechallenge.dev/instructions/">To learn more about the challenge click here</a>. I have been studying Information Technology since i graduated
159        highschool although I was not sure exactly what field I wanted to get into. I was able to get a IT helpdesk job which help me understand the fundamentals but i knew that i wanted to learn more. I later discovered the cloud and was intrigued by
160        the freedom and creativity that could be expressed in the cloud. I began to get curious and that drove me to get my AWS Solutions Architect Associate. I am now working on more projects so that i can score real world experience and even have some
161        fun with it. </p>
162      <h3> Skills </h3>
163      <ul>
164        <li>
165          <div class="weight">Software:</div> Windows 7, 8 and 10; HTML and CSS knowledge. Experience using IDE’s with C++ and Python. Virtualization troubleshooting of virtual machines and VDI’s.</li>
166        <br>
167        <li>
168          <div class="weight">Hardware:</div> Troubleshooting HP printers; general computer builds and repairs; hardware installations and swaps. RAID Arrays, RAM and CPU replacement. Ability to troubleshoot and narrow down problems regarding hardware </li>
169        <br>
170        <li>
171          <div class="weight">Networking:</div> Networking experience (running cables, troubleshooting connections, activating ports, basic router configuration, switches, Wi-Fi router) Familiar with different cabling types such as CAT 5, CAT6, twisted pairs, fiber optic
172          cables. </li>
173        <br>
174        <li>
175          <div class="weight">Support:</div> Helpdesk: escalation and documentation on ticketing system, customer service support (email, phone, and in person). Assisting 40 customers per day. </li>
176        <br>
177        <li>
178          <div class="weight">Cloud Computing:</div> Amazon Web Services, Cloud Architecture, Cloud Infrastructure. </li>
179      </ul>
180      <h3> Experience </h3>
181      <div class="weight"> Navy Federal Credit Union </div>
182      <div class="Right_Side Upwards weight"> Service Desk Member </div>
183      <div class="weight"> Vienna, VA </div>
184      <div class="Right_Side Upwards weight"> Feb 2018 - January 2021 </div>
185      <ul>
186        <li> Provided customer service to 30 customers a day. Talked to customers who needed technical support for their computers and active directory accounts. </li>
187        <br>
188        <li> Alerted management team when a technical outage in the credit union occurred to ensure that the issue gets patched as efficiently as possible. </li>
189        <br>
190        <li> Worked with colleagues in the event of a technical outage to minimize the call queue and effectively troubleshoot for a solution. </li>
191      </ul>
192      <h3> Education </h3>
193      <p class="weight"> George Mason University </p>
194      <div class="Right_Side Upwards weight"> Fairfax, Va </div>
195      <div class="weight"> Information Technology </div>
196      <div class="Right_Side Upwards weight" id="Upwards"> August 2017 - Present </div>
197      <ul>
198        <li> Year Up is a leading one-year career development program with 250 corporate partners around the country; the program includes college-level courses, professional training, and a six-month internship. </li>
199        <br>
200        <li> Earned an Associate Degree from Northern Virginia Community in Information Technology with 67 credits. </li>
201        <br>
202        <li> Working towards a bachelor's degree in Information Technology with 120 credits. </li>
203      </ul>
204      <h3> AWS Solutions Architecture </h3>
205      <div class="weight"> Cloud Computing </div>
206      <div class="Right_Side Upwards weight"> April 2021 </div>
207      <ul>
208        <li> Understands cloud architecture and how to host a highly available website. Able to write simple bash scripts on EC2 instances. </li>
209        <br>
210        <li> Able to execute best practices on security such as private subnets, firewalls, and security groups. </li>
211        <br>
212        <li> Understanding routing on Route 53 latency-based routing geolocation-based routing etc. </li>
213        <br>
214        <li> able to host a static website on S3. </li>
215      </ul>
216
217
218    </div>
219  </div>
220
221  <div id="footer">
222
223    <div class="Counter">
224    </div>
225    <a href="https://www.linkedin.com/in/noah-harris-947b38152/" class="pretty"> Check me out on Linkedin</a>
226  </div>
227
228</body>
229
230</html>

ANSWER

Answered 2022-Jan-04 at 19:50

I advise you to follow many good techniques when developing a responsive webpage, here I explain to you:

  • Replacing in your CSS absolute units such as px for percentages or em. It is always much better to work with relative measurements rather than absolute ones. From my experience, I always try to work with em, here is a conversion from px to em.
  • Using responsive layouts like flex or grid.
  • Adding metadata related to the viewport in the HTML head tag. I can see you haven't written it. As we can read in W3Schools viewport is the user's visible area of a web page. It varies with the device so it will be smaller on a mobile phone than on a computer screen. You should include the following element in all your web pages: <meta name="viewport" content="width=device-width, initial-scale=1.0">

In conclusion, try to avoid absolute positioning because it is not the best option. Try to follow this advice and I am sure your webpage will turn so much better. :D.

Source https://stackoverflow.com/questions/70582850

QUESTION

How do i set a public URL when using EC2

Asked 2021-Dec-23 at 05:09

I have an instance setup for a test site using Amazon Web Services listed under EC2.

I then setup an Elastic IP which as i understand is a static IP.

Once logged into this instance of Windows Server i setup a site in IIS which runs locally.

I have set all the bindings in IIS but struggling to figure out how i assign a public name to this instance so i can view the site in an external browser? I tried entering the IP but that doesnt open anything, not even the standard IIS page?

ANSWER

Answered 2021-Dec-23 at 05:09

Check your firewall if you have opened the port 80 or whatever the IIS is bonded with and also check your security group of the EC2 instance and open the port 80 to the world

Source https://stackoverflow.com/questions/70451289

QUESTION

What will happen if a SSL-configured Nginx reverse proxy pass to an web server without SSL?

Asked 2021-Dec-16 at 09:39

I use Nginx to manage a lot of my web services. They listens different port, but all accessed by the reverse proxy of Nginx within one domain. Such as to access a RESTful-API server I can use http://my-domain/api/, and to access a video server I can use http://my-domain/video.

I have generated a SSL certificate for my-domain and added it into my Nginx conf so my Nginx server is HTTPS now -- But those original servers are still using HTTP.

What will happen when I visit https://my-domain/<path>? Is this as safe as configuring SSL on the original servers?

ANSWER

Answered 2021-Dec-16 at 09:39

One of the goals of making sites be HTTPS is to prevent the transmitted data between two endpoints from being intercepted by outside parties to either be modified, as in a man-in-the-middle attack, or for the data to be stolen and used for bad purposes. On the public Internet, any data transmitted between two endpoints needs to be secured.

On private networks, this need isn't quite so great. Many services do run on just HTTP on private networks just fine. However, there are a couple points to take into consideration:

Make sure unused ports are blocked:

While you may have an NGINX reverse proxy listening on port 443, is port 80 blocked, or can the sites still be accessed via HTTP?

Are the other ports to the services blocked as well? Let's say your web server runs on port 8080, and the NGINX reverse proxy forwards certain traffic to localhost:8080, can the site still be accessed at http://example.com:8080 or https://example.com:8080? One way to prevent this is to use a firewall and block all incoming traffic on any ports you don't intend to accept traffic on. You can always unblock them later, if you add a service that requires that port be opened.

Internal services are accessible by other services on the same server

The next consideration relates to other software that may be running on the server. While it's within a private ecosystem, any service running on the server can access localhost:8080. Since the traffic between the reverse proxy and the web server are not encrypted, that traffic can also be sniffed, even if authorisation is required in order to authenticate localhost:8080. All a rogue service would need to do is monitor the port and wait for a user to login. Then that service can capture everything between the two endpoints.

One strategy to mitigate the dangers created by spyware is to either use virtualisation to separate a single server into logical servers, or use different hardware for things that are not related. This at least keeps things separate so that the people responsible for application A don't think that service X might be something the team running application B is using. Anything out of place will more likely stand out.

For instance, a company website and an internal wiki probably don't belong on the same server.

The simpler we can keep the setup and configuration on the server by limiting what that server's job is, the more easily we can keep tabs on what's happening on the server and prevent data leaks.

Use good security practices

Use good security best practices on the server. For instance, don't run as root. Use a non-root user for administrative tasks. For any services that run which are long lived, don't run them as root.

For instance, NGINX is capable of running as the user www-data. With specific users for different services, we can create groups and assign the different users to them and then modify the file ownership and permissions, using chown and chmod, to ensure that those services only have access to what they need and nothing more. As an example, I've often wondered why NGINX needs read access to logs. It really should, in theory, only need write access to them. If this service were to somehow get compromised, the worst it could do is write a bunch of garbage to the logs, but an attacker might find their hands are tied when it comes to retrieving sensitive information from them.

localhost SSL certs are generally for development only

While I don't recommend this for production, there are ways to make localhost use HTTPS. One is with a self signed certificate. The other uses a tool called mkcert which lets you be your own CA (certificate authority) for issuing SSL certificates. The latter is a great solution, since the browser and other services will implicitly trust the generated certificates, but the general consensus, even by the author of mkcert, is that this is only recommended for development purposes, not production purposes. I've yet to find a good solution for localhost in production. I don't think it exists, and in my experience, I've never seen anyone worry about it.

Source https://stackoverflow.com/questions/70375800

QUESTION

RESTful response is not displaying in Chrome after successful test

Asked 2021-Dec-15 at 22:27

I am working my way through the activities section of my course and have hit a bit of a roadblock. The object of the activity is to display a string of text using a restful service, using the NetBeans IDE.

When I ran the TEST RESTful web services option in Netbeans it worked:

Successful RESTful service test

However, when I run the program all I see in the browser is a blank page:

what is displayed when webservice runs

At first I thought I had coded it incorrectly so I redid the exercise, but still came out with the same result. After one final try I then opened the solution file and have gotten the code correct, but the solution code displays an output, yet mine still does not. Why is the browser not displaying the pathway to the string?

If I type the pathway directly into Chrome it displays exactly as it should do.

I then tried adding a redirect to the index.html file which achieved the desired outcome of the exercise, but I don't think that is in the spirit of the question:

Browser display after redirect

I'm sure there is there a "proper" way of doing this, but I can't work it out. Here is my code:

RestService.java

1package restService;
2
3import javax.ws.rs.core.Context;
4import javax.ws.rs.core.UriInfo;
5import javax.ws.rs.Produces;
6import javax.ws.rs.Consumes;
7import javax.ws.rs.GET;
8import javax.ws.rs.Path;
9import javax.ws.rs.PUT;
10import javax.ws.rs.core.MediaType;
11
12/**
13 * REST Web Service
14 *
15 * @author Matthew
16 */
17@Path(&quot;rest&quot;)
18public class RestSevice {
19
20    @Context
21    private UriInfo context;
22
23    /**
24     * Creates a new instance of RestSevice
25     */
26    public RestSevice() {
27    }
28
29    /**
30     * Retrieves representation of an instance of restService.RestSevice
31     * @return an instance of java.lang.String
32     */
33    @GET
34    @Path(&quot;/banner&quot;)
35    @Produces(MediaType.TEXT_HTML)
36    public String getHtml() {
37        return &quot;&lt;HTML&gt;&lt;body&gt;&lt;h1&gt;This is a RESTful response!&lt;/h1&gt;&lt;/&lt;body&gt;&lt;/html&gt;&quot;;
38    }
39
40    /**
41     * PUT method for updating or creating an instance of RestSevice
42     * @param content representation for the resource
43     */
44    @PUT
45    @Consumes(javax.ws.rs.core.MediaType.TEXT_PLAIN)
46    public void putText(String content) {
47    }
48}
49

index.html

1package restService;
2
3import javax.ws.rs.core.Context;
4import javax.ws.rs.core.UriInfo;
5import javax.ws.rs.Produces;
6import javax.ws.rs.Consumes;
7import javax.ws.rs.GET;
8import javax.ws.rs.Path;
9import javax.ws.rs.PUT;
10import javax.ws.rs.core.MediaType;
11
12/**
13 * REST Web Service
14 *
15 * @author Matthew
16 */
17@Path(&quot;rest&quot;)
18public class RestSevice {
19
20    @Context
21    private UriInfo context;
22
23    /**
24     * Creates a new instance of RestSevice
25     */
26    public RestSevice() {
27    }
28
29    /**
30     * Retrieves representation of an instance of restService.RestSevice
31     * @return an instance of java.lang.String
32     */
33    @GET
34    @Path(&quot;/banner&quot;)
35    @Produces(MediaType.TEXT_HTML)
36    public String getHtml() {
37        return &quot;&lt;HTML&gt;&lt;body&gt;&lt;h1&gt;This is a RESTful response!&lt;/h1&gt;&lt;/&lt;body&gt;&lt;/html&gt;&quot;;
38    }
39
40    /**
41     * PUT method for updating or creating an instance of RestSevice
42     * @param content representation for the resource
43     */
44    @PUT
45    @Consumes(javax.ws.rs.core.MediaType.TEXT_PLAIN)
46    public void putText(String content) {
47    }
48}
49&lt;!DOCTYPE html&gt;
50&lt;!--
51To change this license header, choose License Headers in Project Properties.
52To change this template file, choose Tools | Templates
53and open the template in the editor.
54--&gt;
55&lt;html&gt;
56    &lt;head&gt;
57        &lt;title&gt;RESTful service&lt;/title&gt;
58        &lt;meta charset=&quot;UTF-8&quot;&gt;
59        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
60    &lt;/head&gt;
61    &lt;body&gt;
62        &lt;div&gt;
63            &lt;ul&gt;
64                &lt;meta http-equiv=&quot;Refresh&quot; content=&quot;0; url='http://localhost:8080/RESTservice/webresources/rest/banner'&quot; /&gt;
65            &lt;/ul&gt;
66        &lt;/div&gt;
67    &lt;/body&gt;
68&lt;/html&gt;
69

ANSWER

Answered 2021-Dec-15 at 22:27

After relooking at my code and worked example, I then discovered the way I have coded above is a "proper" way of doing things.

the example had a clickable link that then displayed the pathway, resulting in the correct link.

The blank page I was struggling with, was just an empty link. (kinda feel a bit foolish) and in redirecting automatically. it solved the problem.

Source https://stackoverflow.com/questions/70024622

QUESTION

WebSphere 8 memory leaks

Asked 2021-Dec-13 at 15:46

I have an application deployed to WebSphere 8.5 (the app is developed using java8/Spring 4) and every day I get many dump files, so I decided to analyze it using Eclipse Memory Analyzer and the result is:

enter image description here

The problem is I do not use axis for calling web service, I only use Jersy for Rest Web Services and The default jdk class SoapConnection for soap web services, here is some code examples: For Soap :

1public String soapBind(List&lt;ContextItem&gt; dic, String serviceId, String urlWs, String applicationId) throws SOAPException, Exception {
2    try {
3        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
4        SOAPConnection soapConnection = soapConnectionFactory.createConnection();
5        SOAPMessage msg = soapCall(dic, serviceId, applicationId); // Send SOAP Message to SOAP Server
6
7        String url = urlWs;
8        LOGGER.info(&quot;CALLING WS ....&quot;);
9        SOAPMessage soapResponse = soapConnection.call(msg, url);
10
11        // print SOAP Response
12       
13        //soapResponse.writeTo(System.out);
14        ByteArrayOutputStream out = new ByteArrayOutputStream();
15        soapResponse.writeTo(out);
16        soapConnection.close();
17
18        String strMsg = new String(out.toByteArray());
19        LOGGER.info(&quot;Response SOAP Message: {}&quot;,strMsg);
20        return strMsg;
21
22    } catch (SOAPException ex) {
23        throw ex;
24    } catch (UnsupportedOperationException ex) {
25        throw ex;
26    } catch (Exception ex) {
27        throw ex;
28    }
29}
30

For Rest :

1public String soapBind(List&lt;ContextItem&gt; dic, String serviceId, String urlWs, String applicationId) throws SOAPException, Exception {
2    try {
3        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
4        SOAPConnection soapConnection = soapConnectionFactory.createConnection();
5        SOAPMessage msg = soapCall(dic, serviceId, applicationId); // Send SOAP Message to SOAP Server
6
7        String url = urlWs;
8        LOGGER.info(&quot;CALLING WS ....&quot;);
9        SOAPMessage soapResponse = soapConnection.call(msg, url);
10
11        // print SOAP Response
12       
13        //soapResponse.writeTo(System.out);
14        ByteArrayOutputStream out = new ByteArrayOutputStream();
15        soapResponse.writeTo(out);
16        soapConnection.close();
17
18        String strMsg = new String(out.toByteArray());
19        LOGGER.info(&quot;Response SOAP Message: {}&quot;,strMsg);
20        return strMsg;
21
22    } catch (SOAPException ex) {
23        throw ex;
24    } catch (UnsupportedOperationException ex) {
25        throw ex;
26    } catch (Exception ex) {
27        throw ex;
28    }
29}
30Client client = Client.create();
31 WebResource webResource = client
32 .resource(urlFicheClientProf);
33//
34 ServiceContext serviceContext = this.getServiceContext();
35//
36ObjectMapper mapper = new ObjectMapper();
37
38 ClientResponse response = webResource
39 .queryParam(&quot;customerId&quot;, radical)
40 .queryParam(&quot;serviceContext&quot;,
41 URLEncoder.encode(mapper.writeValueAsString(serviceContext),
42 &quot;UTF-8&quot;))
43 .post(ClientResponse.class);
44

I am wondering why the Axis.Client Out of memory has occurred and how can I fix it. If anyone could help me figure it out I would be very grateful .

ANSWER

Answered 2021-Nov-27 at 17:11

Regarding your first question: Why does Apache Axis2 get used when you use the default JDK class SOAPConnection? The class SOAPConnection is actually just a part of an API that could have different implementations. In your case WebSphere provides an implementation of this API based on Apache Axis2, that's why you are seeing objects of those classes lingering. The SOAPConnection Javadocs state:

The SOAPConnection class is optional. Some implementations may not implement this interface in which case the call to SOAPConnectionFactory.newInstance() (see below) will throw an UnsupportedOperationException.

About the second part of your question, I have a hypothesis. In the Javadocs I could not find if a call to SOAPConnection.close() is mandatory, but usually resource classes with a close() method do require cleaning up or else they create memory or other resource leaks. Your code does call close(), however if an exception occurs somewhere before closing the connection, the execution would jump straight to catch (...) and the connection will not be cleaned up, thus creating a memory leak. Maybe this happens every time a SOAP call throws an exception and this leaked the memory you are observing.

You could solve this by using a try-resource-close pattern described here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html Try the following change in your code.

Edit:

1public String soapBind(List&lt;ContextItem&gt; dic, String serviceId, String urlWs, String applicationId) throws SOAPException, Exception {
2    try {
3        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
4        SOAPConnection soapConnection = soapConnectionFactory.createConnection();
5        SOAPMessage msg = soapCall(dic, serviceId, applicationId); // Send SOAP Message to SOAP Server
6
7        String url = urlWs;
8        LOGGER.info(&quot;CALLING WS ....&quot;);
9        SOAPMessage soapResponse = soapConnection.call(msg, url);
10
11        // print SOAP Response
12       
13        //soapResponse.writeTo(System.out);
14        ByteArrayOutputStream out = new ByteArrayOutputStream();
15        soapResponse.writeTo(out);
16        soapConnection.close();
17
18        String strMsg = new String(out.toByteArray());
19        LOGGER.info(&quot;Response SOAP Message: {}&quot;,strMsg);
20        return strMsg;
21
22    } catch (SOAPException ex) {
23        throw ex;
24    } catch (UnsupportedOperationException ex) {
25        throw ex;
26    } catch (Exception ex) {
27        throw ex;
28    }
29}
30Client client = Client.create();
31 WebResource webResource = client
32 .resource(urlFicheClientProf);
33//
34 ServiceContext serviceContext = this.getServiceContext();
35//
36ObjectMapper mapper = new ObjectMapper();
37
38 ClientResponse response = webResource
39 .queryParam(&quot;customerId&quot;, radical)
40 .queryParam(&quot;serviceContext&quot;,
41 URLEncoder.encode(mapper.writeValueAsString(serviceContext),
42 &quot;UTF-8&quot;))
43 .post(ClientResponse.class);
44public String soapBind(List&lt;ContextItem&gt; dic, String serviceId, String urlWs, String applicationId) throws SOAPException, Exception {
45    try {
46        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
47        try (MySOAPConnection mySoapConnection = new MySOAPConnection(soapConnectionFactory)) {
48            SOAPConnection soapConnection = mySoapConnection.connection;
49            SOAPMessage msg = soapCall(dic, serviceId, applicationId); // Send SOAP Message to SOAP Server
50
51            String url = urlWs;
52            LOGGER.info(&quot;CALLING WS ....&quot;);
53            SOAPMessage soapResponse = soapConnection.call(msg, url);
54
55            // print SOAP Response
56           
57            //soapResponse.writeTo(System.out);
58            ByteArrayOutputStream out = new ByteArrayOutputStream();
59            soapResponse.writeTo(out);
60            
61            String strMsg = new String(out.toByteArray());
62            LOGGER.info(&quot;Response SOAP Message: {}&quot;,strMsg);
63            return strMsg;
64        }
65    } catch (SOAPException ex) {
66        throw ex;
67    } catch (UnsupportedOperationException ex) {
68        throw ex;
69    } catch (Exception ex) {
70        throw ex;
71    }
72}
73
74public class MySOAPConnection implements AutoCloseable {
75
76    public final SOAPConnection connection;
77    
78    public MySOAPConnection(SOAPConnectionFactory soapConnectionFactory)
79    {
80        this.connection = soapConnectionFactory.createConnection();
81    }
82    
83    @Override
84    public void close() throws Exception {
85        this.connection.close();            
86    }
87}
88

Note that when you use try-resource-close, the close() method should not be called explicitly, otherwise you would get double close()!

Source https://stackoverflow.com/questions/69812071

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Web Services

Tutorials and Learning Resources are not available at this moment for Web Services

Share this Page

share link

Get latest updates on Web Services