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

Popular New Releases in HTTP

requests

v2.27.1

Alamofire

Missing Cancellation Parameter

mitmproxy

v8.0.0

echo

actix-web

actix-http: v3.0.4

Popular Libraries in HTTP

requests

by psf doticonpythondoticon

star image 47177 doticonApache-2.0

A simple, yet elegant, HTTP library.

okhttp

by square doticonkotlindoticon

star image 41993 doticonApache-2.0

Square’s meticulous HTTP client for the JVM, Android, and GraalVM.

Alamofire

by Alamofire doticonswiftdoticon

star image 37489 doticonMIT

Elegant HTTP Networking in Swift

wrk

by wg doticoncdoticon

star image 30791 doticonNOASSERTION

Modern HTTP benchmarking tool

mitmproxy

by mitmproxy doticonpythondoticon

star image 26747 doticonMIT

An interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers.

echo

by labstack doticongodoticon

star image 21826 doticonMIT

High performance, minimalist Go web framework

Perfect

by PerfectlySoft doticonswiftdoticon

star image 13879 doticonNOASSERTION

Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)

actix-web

by actix doticonrustdoticon

star image 13778 doticonNOASSERTION

Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.

uWebSockets

by uNetworking doticonc++doticon

star image 13721 doticonApache-2.0

Simple, secure & standards compliant web server for the most demanding of applications

Trending New libraries in HTTP

workflow

by sogou doticonc++doticon

star image 7431 doticonApache-2.0

Parallel Computing and Asynchronous Networking Engine ⭐️⭐️⭐️

plow

by six-ddc doticongodoticon

star image 2938 doticonApache-2.0

A high-performance HTTP benchmarking tool with real-time web UI and terminal displaying

updog

by sc0tfree doticonpythondoticon

star image 1235 doticonMIT

Updog is a replacement for Python's SimpleHTTPServer. It allows uploading and downloading via HTTP/S, can set ad hoc SSL certificates and use http basic auth.

webman

by walkor doticonphpdoticon

star image 884 doticonMIT

Probably the fastest PHP web framework in the world.

ntex

by ntex-rs doticonrustdoticon

star image 879 doticonMIT

framework for composable networking services

webify

by beefsack doticongodoticon

star image 861 doticonMIT

Turn shell commands into web services

ff-proxy

by TimeToogo doticoncdoticon

star image 703 doticonMIT

A UDP to TCP proxy server for sending HTTP requests with zero roundtrips

atlantis

by ProxymanApp doticonswiftdoticon

star image 695 doticonApache-2.0

A lightweight and powerful iOS framework for intercepting HTTP/HTTPS Traffic.

darkhttpd

by emikulic doticoncdoticon

star image 629 doticon

When you need a web server in a hurry.

Top Authors in HTTP

1

apache

23 Libraries

star icon6808

2

substack

13 Libraries

star icon2774

3

contributte

11 Libraries

star icon113

4

jetty-project

10 Libraries

star icon235

5

tokuhirom

10 Libraries

star icon61

6

google

9 Libraries

star icon13191

7

mafintosh

9 Libraries

star icon1151

8

ZewoGraveyard

9 Libraries

star icon216

9

sindresorhus

8 Libraries

star icon18622

10

php-http

8 Libraries

star icon1368

1

23 Libraries

star icon6808

2

13 Libraries

star icon2774

3

11 Libraries

star icon113

4

10 Libraries

star icon235

5

10 Libraries

star icon61

6

9 Libraries

star icon13191

7

9 Libraries

star icon1151

8

9 Libraries

star icon216

9

8 Libraries

star icon18622

10

8 Libraries

star icon1368

Trending Kits in HTTP

The JavaScript HTTP request libraries play a crucial role in web development. It provides a convenient and efficient way to send and receive data over the Internet. It helps make HTTP requests, handle headers, and manage cookies. It helps in dealing with various protocols abstracted away by HTTP request libraries.  

 

JavaScript HTTP request libraries provide a simple and unified API. The developers can use it to send requests and handle responses. JavaScript libraries help manage Cross-Origin Resource Sharing. It is a security mechanism imposed by browsers. It helps restrict web pages from accessing resources on different domains. JavaScript HTTP request libraries are essential tools for modern web development. They streamline the HTTP requests process and handle complexities, asynchronous operations, and error handling. It provides features that simplify the development of robust and performant web applications. JavaScript is single-threaded, meaning it can only execute one task simultaneously.  

 

Here are the best libraries organized by use cases. The best libraries are Axios, jQuery, Request, Super agent, Got, Node-fetch, and Axios-retry. A detailed review of each library follows.   

 

Let's look at each library in detail. The links allow you to access package commands, installation notes, and code snippets.  

axios:  

  • It is a popular JavaScript library. It simplifies making HTTP requests from a browser or a Node.js environment.  
  • It supports various methods like GET, POST, PUT, and DELETE. It straightforwardly handles request and response objects.  
  • It leverages JavaScript promises. It simplifies handling asynchronous operations and enables better code organization.  
  • It is designed to work across different browsers. 

jquery:  

  • It was designed to simplify JavaScript programming. It provides a concise syntax and a set of powerful utilities.  
  • The selector engine allows developers to select elements using CSS-like syntax. It makes it intuitive and easy to use.  
  • It abstracts away many of these browser-specific quirks, providing a consistent API. It works across various browsers.  
  • It is extensible architecture allows developers to create plugins. It enhances its functionality or integrates with other libraries and frameworks.  

request:  

  • It enables the retrieval of data from external servers. It also facilitates the submission of data to external servers.  
  • It includes error-handling mechanisms. It handles scenarios such as network failures, server errors, or timeouts.  
  • It provides the means to send HTTP requests to API endpoints and retrieve responses. It helps integrate the obtained data into the application.  
  • It empowers developers to build robust and interactive web applications. They interact with external servers.  

superagent:  

  • It supports both promises and traditional callbacks for handling responses.  
  • It provides methods for manipulating request headers, query parameters, and request bodies.  
  • It offers a middleware system that enables developers to extend its functionality.  
  • It includes built-in features that facilitate testing HTTP endpoints and APIs.  

got:  

  • It is designed to have a simple and intuitive API, making it easy to use for developers.  
  • It leverages Promises, which are a fundamental part of modern JavaScript. It helps handle asynchronous operations.  
  • It includes built-in error handling and throws exceptions for common HTTP errors.  
  • It has gained popularity in the JavaScript ecosystem. It has an active community of developers.  

node-fetch:  

  • It offers a simple and intuitive API. It helps make HTTP requests, like the Fetch API, available in modern browsers.  
  • It utilizes JavaScript promises, making it compatible with the asynchronous programming paradigm.  
  • It can be extended or combined with other libraries to enhance its functionality.  
  • It has an active developer community that contributes to its maintenance and improvement.  

axios-retry:  

  • It is an extension of the popular JavaScript HTTP client library called Axios.  
  • It enables your application to handle such scenarios by retrying failed requests. It provides the network a chance to stabilize.  
  • It provides flexible configuration options. It allows you to customize the retry behavior according to your specific requirements.  
  • It enhances the reliability, resilience, and error-handling capabilities of your application.  

FAQ:  

1. What is an asynchronous HTTP request, and why is it used?  

An asynchronous HTTP request is a type of HTTP request. A client sends it to a server. But the client does not wait for the server's response before continuing with other tasks. Asynchronous HTTP requests are used to improve the responsiveness of web applications. Here are some reasons why they are beneficial:  

  • Improved performance  
  • Concurrent processing  
  • Resource optimization  
  • Real-time updates  


2. What are the different types of request methods in the JavaScript HTTP library?  

In JavaScript, the most used HTTP library is the Fetch API. It provides a simple and powerful way to make HTTP requests. The Fetch API supports several request methods to interact with web servers. Here are the most used request methods:  

  • GET  
  • POST  
  • PUT  
  • DELETE  
  • PATCH  
  • HEAD  
  • OPTIONS  


3. How do you interpret a response's HTTP status code when making requests?  

When making requests, you can interpret the response's status code. It will help you understand the outcome of your request. The HTTP status code is a three-digit numeric code. It provides information about the server's response to the request. Here's how you can interpret the HTTP status codes in JavaScript:  

  • Informational responses (1xx)  
  • Successful responses (2xx)  
  • Redirection responses (3xx)  
  • Client error responses (4xx)  
  • Server error responses (5xx)  


4. Can a Promise-based HTTP client be used for AJAX requests?  

Yes, there are several Promise-based HTTP clients. It can be used for making AJAX requests in JavaScript. Here are a few popular options:  

  • Axios  
  • Fetch API  
  • jQuery  

 

5. What advantages does Axios have over other JavaScript http libraries?  

Axios is a popular JavaScript library used for making HTTP requests. It offers several advantages over other JavaScript HTTP libraries. Here are some of them:  

  • Simplicity  
  • Promises-based  
  • Browser and Node.js support  
  • Cross-platform compatibility  
  • Intercepting requests and responses  
  • Built-in CSRF protection  
  • Canceling requests  
  • Rich request and response handling        

Here are some of the famous Node JS HTTP Request Libraries. The use cases of these libraries include Server-side Web Apps, Mobile App Development, Data Processing, Data Analysis, and Network Monitoring.


Node.js HTTP Request Libraries are libraries that allow Node.js developers to make requests to web servers in order to retrieve data. This can be helpful when building web applications that need to pull in external data from other web servers. Examples of popular Node.js HTTP Request Libraries are Axios, Request, and Superagent.


Let us look at some of these famous libraries. 

axios

  • Automatically transforms all request and response data into JSON, making it easier to handle data.
  • Supports interceptors which can be used to modify or transform requests or responses before they are handled by then or catch.
  • Supports automatic token refresh.

fetch

  • Supports cancelable requests and allows developers to abort requests at any point. 
  • Supports a wide range of HTTP methods beyond the standard GET and POST. 
  • Provides a Promise-based API, which simplifies the process of making asynchronous requests. 

request

  • Provides full access to all Node.js features, including streams, event emitters, and files.
  • Is highly configurable and can be used to set timeouts, retry requests, and more.
  • Has built-in support for gzip and deflate encoding.

superagent

  • Allows easy setting headers, cookies, and other request parameters. 
  • Is highly configurable and supports many features that help developers quickly and easily request HTTP.  
  • Supports multipart encoding, allowing developers to send binary data easily. 

nock

  • Allows users to easily create custom request matchers, allowing users to create more powerful and precise requests. 
  • Users can record and replay their requests, making debugging and testing easy.  
  • Provides a sandbox for users to test their requests in isolation without making live calls or affecting the external environment. 

node-fetch

  • Supports global agent pooling and request pooling.
  • Allows developers to use the same API for both server and client-side requests.
  • Is designed to be lightweight and fast, making it ideal for applications that require rapid response times.

r2

  • Provides support for the latest security protocols, such as TLS 1.3.
  • Support for advanced HTTP methodologies such as HTTP/2 and WebSocket.
  • Allows for the implementation of custom middleware.

needle

  • Has built-in support for parsing JSON and can be used to create custom parsers for other formats.  
  • Is well-documented and provides a comprehensive set of APIs for making HTTP requests.  
  • Is optimized for low latency and high throughput, making it suitable for various applications. 

unirest-nodejs

  • Has built-in support for automatically following redirects.
  • Allows to send both synchronous and asynchronous requests.
  • Has built-in support for automatically compressing and decompressing requests and responses.

hyperquest

  • Has built-in support for caching and retrying requests, making it easy to build resilient applications.  
  • Supports server-side data serialization and deserialization, allowing developers to transform data between client and server quickly.  
  • Is built on a minimalistic core, making it suitable for applications that need a small footprint. 

Trending Discussions on HTTP

Error: require() of ES modules is not supported when importing node-fetch

Java, Intellij IDEA problem Unrecognized option: --add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED

Springboot 2.6.0 / Spring fox 3 - Failed to start bean 'documentationPluginsBootstrapper'

Allow insecure protocols, android gradle

ASP.NET Core 6 how to access Configuration during startup

throwError(error) is now deprecated, but there is no new Error(HttpErrorResponse)

How to use appsettings.json in Asp.net core 6 Program.cs file

android:exported needs to be explicitly specified for <activity>. Apps targeting Android 12 and higher are required to specify

uploaded an APK which has an activity,activity alias,service or broadcast receiver with intentfilter, but without 'android : exported' property set

What's the mathematical reason behind Python choosing to round integer division toward negative infinity?

QUESTION

Error: require() of ES modules is not supported when importing node-fetch

Asked 2022-Mar-28 at 07:04

I'm creating a program to analyze security camera streams and got stuck on the very first line. At the moment my .js file has nothing but the import of node-fetch and it gives me an error message. What am I doing wrong?

Running Ubuntu 20.04.2 LTS in Windows Subsystem for Linux.

Node version:

1user@MYLLYTIN:~/CAMSERVER$ node -v
2v14.17.6
3

node-fetch package version:

1user@MYLLYTIN:~/CAMSERVER$ node -v
2v14.17.6
3user@MYLLYTIN:~/CAMSERVER$ npm v node-fetch
4
5node-fetch@3.0.0 | MIT | deps: 2 | versions: 63
6A light-weight module that brings Fetch API to node.js
7https://github.com/node-fetch/node-fetch
8
9keywords: fetch, http, promise, request, curl, wget, xhr, whatwg
10
11dist
12.tarball: https://registry.npmjs.org/node-fetch/-/node-fetch-3.0.0.tgz
13.shasum: 79da7146a520036f2c5f644e4a26095f17e411ea
14.integrity: sha512-bKMI+C7/T/SPU1lKnbQbwxptpCrG9ashG+VkytmXCPZyuM9jB6VU+hY0oi4lC8LxTtAeWdckNCTa3nrGsAdA3Q==
15.unpackedSize: 75.9 kB
16
17dependencies:
18data-uri-to-buffer: ^3.0.1 fetch-blob: ^3.1.2         
19
20maintainers:
21- endless <jimmy@warting.se>
22- bitinn <bitinn@gmail.com>
23- timothygu <timothygu99@gmail.com>
24- akepinski <npm@kepinski.ch>
25
26dist-tags:
27latest: 3.0.0        next: 3.0.0-beta.10  
28
29published 3 days ago by endless <jimmy@warting.se>
30

esm package version:

1user@MYLLYTIN:~/CAMSERVER$ node -v
2v14.17.6
3user@MYLLYTIN:~/CAMSERVER$ npm v node-fetch
4
5node-fetch@3.0.0 | MIT | deps: 2 | versions: 63
6A light-weight module that brings Fetch API to node.js
7https://github.com/node-fetch/node-fetch
8
9keywords: fetch, http, promise, request, curl, wget, xhr, whatwg
10
11dist
12.tarball: https://registry.npmjs.org/node-fetch/-/node-fetch-3.0.0.tgz
13.shasum: 79da7146a520036f2c5f644e4a26095f17e411ea
14.integrity: sha512-bKMI+C7/T/SPU1lKnbQbwxptpCrG9ashG+VkytmXCPZyuM9jB6VU+hY0oi4lC8LxTtAeWdckNCTa3nrGsAdA3Q==
15.unpackedSize: 75.9 kB
16
17dependencies:
18data-uri-to-buffer: ^3.0.1 fetch-blob: ^3.1.2         
19
20maintainers:
21- endless <jimmy@warting.se>
22- bitinn <bitinn@gmail.com>
23- timothygu <timothygu99@gmail.com>
24- akepinski <npm@kepinski.ch>
25
26dist-tags:
27latest: 3.0.0        next: 3.0.0-beta.10  
28
29published 3 days ago by endless <jimmy@warting.se>
30user@MYLLYTIN:~/CAMSERVER$ npm v esm
31
32esm@3.2.25 | MIT | deps: none | versions: 140
33Tomorrow's ECMAScript modules today!
34https://github.com/standard-things/esm#readme
35
36keywords: commonjs, ecmascript, export, import, modules, node, require
37
38dist
39.tarball: https://registry.npmjs.org/esm/-/esm-3.2.25.tgz
40.shasum: 342c18c29d56157688ba5ce31f8431fbb795cc10
41.integrity: sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==
42.unpackedSize: 308.6 kB
43
44maintainers:
45- jdalton <john.david.dalton@gmail.com>
46
47dist-tags:
48latest: 3.2.25  
49
50published over a year ago by jdalton <john.david.dalton@gmail.com>
51

Contents of the .js file (literally nothing but the import):

1user@MYLLYTIN:~/CAMSERVER$ node -v
2v14.17.6
3user@MYLLYTIN:~/CAMSERVER$ npm v node-fetch
4
5node-fetch@3.0.0 | MIT | deps: 2 | versions: 63
6A light-weight module that brings Fetch API to node.js
7https://github.com/node-fetch/node-fetch
8
9keywords: fetch, http, promise, request, curl, wget, xhr, whatwg
10
11dist
12.tarball: https://registry.npmjs.org/node-fetch/-/node-fetch-3.0.0.tgz
13.shasum: 79da7146a520036f2c5f644e4a26095f17e411ea
14.integrity: sha512-bKMI+C7/T/SPU1lKnbQbwxptpCrG9ashG+VkytmXCPZyuM9jB6VU+hY0oi4lC8LxTtAeWdckNCTa3nrGsAdA3Q==
15.unpackedSize: 75.9 kB
16
17dependencies:
18data-uri-to-buffer: ^3.0.1 fetch-blob: ^3.1.2         
19
20maintainers:
21- endless <jimmy@warting.se>
22- bitinn <bitinn@gmail.com>
23- timothygu <timothygu99@gmail.com>
24- akepinski <npm@kepinski.ch>
25
26dist-tags:
27latest: 3.0.0        next: 3.0.0-beta.10  
28
29published 3 days ago by endless <jimmy@warting.se>
30user@MYLLYTIN:~/CAMSERVER$ npm v esm
31
32esm@3.2.25 | MIT | deps: none | versions: 140
33Tomorrow's ECMAScript modules today!
34https://github.com/standard-things/esm#readme
35
36keywords: commonjs, ecmascript, export, import, modules, node, require
37
38dist
39.tarball: https://registry.npmjs.org/esm/-/esm-3.2.25.tgz
40.shasum: 342c18c29d56157688ba5ce31f8431fbb795cc10
41.integrity: sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==
42.unpackedSize: 308.6 kB
43
44maintainers:
45- jdalton <john.david.dalton@gmail.com>
46
47dist-tags:
48latest: 3.2.25  
49
50published over a year ago by jdalton <john.david.dalton@gmail.com>
51user@MYLLYTIN:~/CAMSERVER$ cat server.js 
52import fetch from "node-fetch";
53

Result:

1user@MYLLYTIN:~/CAMSERVER$ node -v
2v14.17.6
3user@MYLLYTIN:~/CAMSERVER$ npm v node-fetch
4
5node-fetch@3.0.0 | MIT | deps: 2 | versions: 63
6A light-weight module that brings Fetch API to node.js
7https://github.com/node-fetch/node-fetch
8
9keywords: fetch, http, promise, request, curl, wget, xhr, whatwg
10
11dist
12.tarball: https://registry.npmjs.org/node-fetch/-/node-fetch-3.0.0.tgz
13.shasum: 79da7146a520036f2c5f644e4a26095f17e411ea
14.integrity: sha512-bKMI+C7/T/SPU1lKnbQbwxptpCrG9ashG+VkytmXCPZyuM9jB6VU+hY0oi4lC8LxTtAeWdckNCTa3nrGsAdA3Q==
15.unpackedSize: 75.9 kB
16
17dependencies:
18data-uri-to-buffer: ^3.0.1 fetch-blob: ^3.1.2         
19
20maintainers:
21- endless <jimmy@warting.se>
22- bitinn <bitinn@gmail.com>
23- timothygu <timothygu99@gmail.com>
24- akepinski <npm@kepinski.ch>
25
26dist-tags:
27latest: 3.0.0        next: 3.0.0-beta.10  
28
29published 3 days ago by endless <jimmy@warting.se>
30user@MYLLYTIN:~/CAMSERVER$ npm v esm
31
32esm@3.2.25 | MIT | deps: none | versions: 140
33Tomorrow's ECMAScript modules today!
34https://github.com/standard-things/esm#readme
35
36keywords: commonjs, ecmascript, export, import, modules, node, require
37
38dist
39.tarball: https://registry.npmjs.org/esm/-/esm-3.2.25.tgz
40.shasum: 342c18c29d56157688ba5ce31f8431fbb795cc10
41.integrity: sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==
42.unpackedSize: 308.6 kB
43
44maintainers:
45- jdalton <john.david.dalton@gmail.com>
46
47dist-tags:
48latest: 3.2.25  
49
50published over a year ago by jdalton <john.david.dalton@gmail.com>
51user@MYLLYTIN:~/CAMSERVER$ cat server.js 
52import fetch from "node-fetch";
53user@MYLLYTIN:~/CAMSERVER$ node -r esm server.js 
54/home/user/CAMSERVER/node_modules/node-fetch/src/index.js:1
55Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/user/CAMSERVER/node_modules/node-fetch/src/index.js
56require() of ES modules is not supported.
57require() of /home/user/CAMSERVER/node_modules/node-fetch/src/index.js from /home/user/CAMSERVER/server.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
58Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/user/CAMSERVER/node_modules/node-fetch/package.json.
59
60    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1089:13) {
61  code: 'ERR_REQUIRE_ESM'
62}
63user@MYLLYTIN:~/CAMSERVER$ 
64

ANSWER

Answered 2022-Feb-25 at 00:00

Use ESM syntax, also use one of these methods before running the file.

  1. specify "type":"module" in package.json
  2. Or use this flag --input-type=module when running the file
  3. Or use .mjs file extension

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

QUESTION

Java, Intellij IDEA problem Unrecognized option: --add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED

Asked 2022-Mar-26 at 15:23

I have newly installed

1IntelliJ IDEA 2021.2 (Ultimate Edition)
2Build #IU-212.4746.92, built on July 27, 2021
3Licensed to XXXXXX
4Subscription is active until August 15, 2021.
5Runtime version: 11.0.11+9-b1504.13 amd64
6VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
7Linux 5.4.0-80-generic
8GC: G1 Young Generation, G1 Old Generation
9Memory: 2048M
10Cores: 3
11
12Kotlin: 212-1.5.10-release-IJ4746.92
13Current Desktop: X-Cinnamon
14

I cloned project I work with on other workstation without issues, but cannot start any class with main method and IDEA says:

1IntelliJ IDEA 2021.2 (Ultimate Edition)
2Build #IU-212.4746.92, built on July 27, 2021
3Licensed to XXXXXX
4Subscription is active until August 15, 2021.
5Runtime version: 11.0.11+9-b1504.13 amd64
6VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
7Linux 5.4.0-80-generic
8GC: G1 Young Generation, G1 Old Generation
9Memory: 2048M
10Cores: 3
11
12Kotlin: 212-1.5.10-release-IJ4746.92
13Current Desktop: X-Cinnamon
14Abnormal build process termination: 
15/usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java -Xmx700m -Djava.awt.headless=true -Djava.endorsed.dirs=\"\" -Dcompile.parallel=false -Drebuild.on.dependency.change=true -Djdt.compiler.useSingleThread=true -Daether.connector.resumeDownloads=false -Dio.netty.initialSeedUniquifier=-5972351880001011455 -Dfile.encoding=UTF-8 -Duser.language=en -Duser.country=US -Didea.paths.selector=IntelliJIdea2021.2 -Didea.home.path=/home/pm/idea-IU-212.4746.92 -Didea.config.path=/home/pm/.config/JetBrains/IntelliJIdea2021.2 -Didea.plugins.path=/home/pm/.local/share/JetBrains/IntelliJIdea2021.2 -Djps.log.dir=/home/pm/.cache/JetBrains/IntelliJIdea2021.2/log/build-log -Djps.fallback.jdk.home=/home/pm/idea-IU-212.4746.92/jbr -Djps.fallback.jdk.version=11.0.11 -Dio.netty.noUnsafe=true -Djava.io.tmpdir=/home/pm/.cache/JetBrains/IntelliJIdea2021.2/compile-server/rfg-survey-api_cc70fc05/_temp_ -Djps.backward.ref.index.builder=true -Djps.track.ap.dependencies=false --add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED -Dtmh.instrument.annotations=true -Dtmh.generate.line.numbers=true -Dkotlin.incremental.compilation=true -Dkotlin.incremental.compilation.js=true -Dkotlin.daemon.enabled -Dkotlin.daemon.client.alive.path=\"/tmp/kotlin-idea-12426594439704512301-is-running\" -classpath /home/pm/idea-IU-212.4746.92/plugins/java/lib/jps-launcher.jar:/usr/lib/jvm/java-1.8.0-openjdk-amd64/lib/tools.jar org.jetbrains.jps.cmdline.Launcher /home/pm/idea-IU-212.4746.92/lib/slf4j.jar:/home/pm/idea-IU-212.4746.92/lib/idea_rt.jar:/home/pm/idea-IU-212.4746.92/lib/platform-api.jar:/home/pm/idea-IU-212.4746.92/plugins/java/lib/maven-resolver-transport-file-1.3.3.jar:/home/pm/idea-IU-212.4746.92/lib/forms_rt.jar:/home/pm/idea-IU-212.4746.92/lib/util.jar:/home/pm/idea-IU-212.4746.92/lib/annotations.jar:/home/pm/idea-IU-212.4746.92/lib/3rd-party.jar:/home/pm/idea-IU-212.4746.92/lib/kotlin-stdlib-jdk8.jar:/home/pm/idea-IU-212.4746.92/plugins/java/lib/maven-resolver-connector-basic-1.3.3.jar:/home/pm/idea-IU-212.4746.92/lib/jna-platform.jar:/home/pm/idea-IU-212.4746.92/lib/protobuf-java-3.15.8.jar:/home/pm/idea-IU-212.4746.92/plugins/java/lib/jps-builders-6.jar:/home/pm/idea-IU-212.4746.92/plugins/java/lib/javac2.jar:/home/pm/idea-IU-212.4746.92/plugins/java/lib/aether-dependency-resolver.jar:/home/pm/idea-IU-212.4746.92/plugins/java/lib/jps-builders.jar:/home/pm/idea-IU-212.4746.92/plugins/java/lib/jps-javac-extension-1.jar:/home/pm/idea-IU-212.4746.92/lib/jna.jar:/home/pm/idea-IU-212.4746.92/lib/jps-model.jar:/home/pm/idea-IU-212.4746.92/plugins/java/lib/maven-resolver-transport-http-1.3.3.jar:/home/pm/idea-IU-212.4746.92/plugins/JavaEE/lib/jasper-v2-rt.jar:/home/pm/idea-IU-212.4746.92/plugins/Kotlin/lib/kotlin-reflect.jar:/home/pm/idea-IU-212.4746.92/plugins/Kotlin/lib/kotlin-plugin.jar:/home/pm/idea-IU-212.4746.92/plugins/ant/lib/ant-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/uiDesigner/lib/jps/java-guiForms-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/eclipse/lib/eclipse-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/eclipse/lib/eclipse-common.jar:/home/pm/idea-IU-212.4746.92/plugins/IntelliLang/lib/java-langInjection-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/Groovy/lib/groovy-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/Groovy/lib/groovy-constants-rt.jar:/home/pm/idea-IU-212.4746.92/plugins/maven/lib/maven-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/gradle-java/lib/gradle-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/devkit/lib/devkit-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/javaFX/lib/javaFX-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/javaFX/lib/javaFX-common.jar:/home/pm/idea-IU-212.4746.92/plugins/JavaEE/lib/javaee-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/webSphereIntegration/lib/jps/javaee-appServers-websphere-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/weblogicIntegration/lib/jps/javaee-appServers-weblogic-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/JPA/lib/jps/javaee-jpa-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/Grails/lib/groovy-grails-jps.jar:/home/pm/idea-IU-212.4746.92/plugins/Grails/lib/groovy-grails-compilerPatch.jar:/home/pm/idea-IU-212.4746.92/plugins/Kotlin/lib/jps/kotlin-jps-plugin.jar:/home/pm/idea-IU-212.4746.92/plugins/Kotlin/lib/kotlin-jps-common.jar:/home/pm/idea-IU-212.4746.92/plugins/Kotlin/lib/kotlin-common.jar org.jetbrains.jps.cmdline.BuildMain 127.0.0.1 34781 9f0681bb-da2a-48db-8344-900ddeb29804 /home/pm/.cache/JetBrains/IntelliJIdea2021.2/compile-server
16Unrecognized option: --add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED
17Error: Could not create the Java Virtual Machine.
18Error: A fatal exception has occurred. Program will exit.
19

I found other comment to check Lombok works and I see it is fine.

How to fix the problem?

ANSWER

Answered 2021-Jul-28 at 07:22

You are running the project via Java 1.8 and add the --add-opens option to the runner. However Java 1.8 does not support it.

So, the first option is to use Java 11 to run the project, as Java 11 can recognize this VM option.

Another solution is to find a place where --add-opens is added and remove it. Check Run configuration in IntelliJ IDEA (VM options field) and Maven/Gradle configuration files for argLine (Maven) and jvmArgs (Gradle)

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

QUESTION

Springboot 2.6.0 / Spring fox 3 - Failed to start bean 'documentationPluginsBootstrapper'

Asked 2022-Mar-25 at 06:14

I'm trying to initiate a Springboot project using Open Jdk 15, Springboot 2.6.0, Springfox 3. We are working on a project that replaced Netty as the webserver and used Jetty instead because we do not need a non-blocking environment.

In the code we depend primarily on Reactor API (Flux, Mono), so we can not remove org.springframework.boot:spring-boot-starter-webflux dependencies.

I replicated the problem that we have in a new project.: https://github.com/jvacaq/spring-fox.

I figured out that these lines in our build.gradle file are the origin of the problem.

1compile("org.springframework.boot:spring-boot-starter-web") {
2   exclude module: "spring-boot-starter-tomcat"
3}
4compile("org.springframework.boot:spring-boot-starter-jetty")
5

Here is the build.gradle file:

1compile("org.springframework.boot:spring-boot-starter-web") {
2   exclude module: "spring-boot-starter-tomcat"
3}
4compile("org.springframework.boot:spring-boot-starter-jetty")
5plugins {
6    id 'org.springframework.boot' version '2.6.0'
7    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
8    id 'java'
9}
10
11group = 'com.example'
12version = '0.0.1-SNAPSHOT'
13sourceCompatibility = '11'
14
15repositories {
16    mavenCentral()
17}
18
19dependencies {
20    compile("org.springframework.boot:spring-boot-starter-web") {
21        exclude module: "spring-boot-starter-tomcat"
22    }
23    compile("org.springframework.boot:spring-boot-starter-jetty")
24    implementation 'org.springframework.boot:spring-boot-starter-webflux'
25    testImplementation 'org.springframework.boot:spring-boot-starter-test'
26    testImplementation 'io.projectreactor:reactor-test'
27    implementation "io.springfox:springfox-boot-starter:3.0.0"
28}
29
30test {
31    useJUnitPlatform()
32}
33
34

I issued the command gradle clean bootrun. The result is this error:

1compile("org.springframework.boot:spring-boot-starter-web") {
2   exclude module: "spring-boot-starter-tomcat"
3}
4compile("org.springframework.boot:spring-boot-starter-jetty")
5plugins {
6    id 'org.springframework.boot' version '2.6.0'
7    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
8    id 'java'
9}
10
11group = 'com.example'
12version = '0.0.1-SNAPSHOT'
13sourceCompatibility = '11'
14
15repositories {
16    mavenCentral()
17}
18
19dependencies {
20    compile("org.springframework.boot:spring-boot-starter-web") {
21        exclude module: "spring-boot-starter-tomcat"
22    }
23    compile("org.springframework.boot:spring-boot-starter-jetty")
24    implementation 'org.springframework.boot:spring-boot-starter-webflux'
25    testImplementation 'org.springframework.boot:spring-boot-starter-test'
26    testImplementation 'io.projectreactor:reactor-test'
27    implementation "io.springfox:springfox-boot-starter:3.0.0"
28}
29
30test {
31    useJUnitPlatform()
32}
33
34 gradle clean bootrun                                                                                                                                                                                                               
35
36> Task :bootRun FAILED
37
38  .   ____          _            __ _ _
39 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
40( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
41 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
42  '  |____| .__|_| |_|_| |_\__, | / / / /
43 =========|_|==============|___/=/_/_/_/
44 :: Spring Boot ::                (v2.6.0)
45
462021-11-19 09:41:06.665  INFO 16666 --- [           main] c.e.springfox.SpringFoxApplication       : Starting SpringFoxApplication using Java 15.0.2 on advance-Inspiron-5379 with PID 16666 (/home/advance/projects/spring-fox/build/classes/java/main started by advance in /home/advance/projects/spring-fox)
472021-11-19 09:41:06.666  INFO 16666 --- [           main] c.e.springfox.SpringFoxApplication       : No active profile set, falling back to default profiles: default
482021-11-19 09:41:07.294  INFO 16666 --- [           main] org.eclipse.jetty.util.log               : Logging initialized @1132ms to org.eclipse.jetty.util.log.Slf4jLog
492021-11-19 09:41:07.396  INFO 16666 --- [           main] o.s.b.w.e.j.JettyServletWebServerFactory : Server initialized with port: 8080
502021-11-19 09:41:07.398  INFO 16666 --- [           main] org.eclipse.jetty.server.Server          : jetty-9.4.44.v20210927; built: 2021-09-27T23:02:44.612Z; git: 8da83308eeca865e495e53ef315a249d63ba9332; jvm 15.0.2+7-27
512021-11-19 09:41:07.417  INFO 16666 --- [           main] o.e.j.s.h.ContextHandler.application     : Initializing Spring embedded WebApplicationContext
522021-11-19 09:41:07.417  INFO 16666 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 713 ms
532021-11-19 09:41:07.474  INFO 16666 --- [           main] org.eclipse.jetty.server.session         : DefaultSessionIdManager workerName=node0
542021-11-19 09:41:07.474  INFO 16666 --- [           main] org.eclipse.jetty.server.session         : No SessionScavenger set, using defaults
552021-11-19 09:41:07.475  INFO 16666 --- [           main] org.eclipse.jetty.server.session         : node0 Scavenging every 660000ms
562021-11-19 09:41:07.480  INFO 16666 --- [           main] o.e.jetty.server.handler.ContextHandler  : Started o.s.b.w.e.j.JettyEmbeddedWebAppContext@6aa3bfc{application,/,[file:///tmp/jetty-docbase.8080.2024342829220941812/, jar:file:/home/advance/.gradle/caches/modules-2/files-2.1/io.springfox/springfox-swagger-ui/3.0.0/1e665fbe22148f7c36fa8a08e515a0047cd4390b/springfox-swagger-ui-3.0.0.jar!/META-INF/resources],AVAILABLE}
572021-11-19 09:41:07.480  INFO 16666 --- [           main] org.eclipse.jetty.server.Server          : Started @1318ms
582021-11-19 09:41:07.920  INFO 16666 --- [           main] o.e.j.s.h.ContextHandler.application     : Initializing Spring DispatcherServlet 'dispatcherServlet'
592021-11-19 09:41:07.920  INFO 16666 --- [           main] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
602021-11-19 09:41:07.921  INFO 16666 --- [           main] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
612021-11-19 09:41:07.931  INFO 16666 --- [           main] o.e.jetty.server.AbstractConnector       : Started ServerConnector@2643d762{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
622021-11-19 09:41:07.932  INFO 16666 --- [           main] o.s.b.web.embedded.jetty.JettyWebServer  : Jetty started on port(s) 8080 (http/1.1) with context path '/'
632021-11-19 09:41:07.934  WARN 16666 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null
642021-11-19 09:41:07.949  INFO 16666 --- [           main] o.e.jetty.server.AbstractConnector       : Stopped ServerConnector@2643d762{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
652021-11-19 09:41:07.950  INFO 16666 --- [           main] org.eclipse.jetty.server.session         : node0 Stopped scavenging
662021-11-19 09:41:07.951  INFO 16666 --- [           main] o.e.j.s.h.ContextHandler.application     : Destroying Spring FrameworkServlet 'dispatcherServlet'
672021-11-19 09:41:07.951  INFO 16666 --- [           main] o.e.jetty.server.handler.ContextHandler  : Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext@6aa3bfc{application,/,[file:///tmp/jetty-docbase.8080.2024342829220941812/, jar:file:/home/advance/.gradle/caches/modules-2/files-2.1/io.springfox/springfox-swagger-ui/3.0.0/1e665fbe22148f7c36fa8a08e515a0047cd4390b/springfox-swagger-ui-3.0.0.jar!/META-INF/resources],STOPPED}
682021-11-19 09:41:07.958  INFO 16666 --- [           main] ConditionEvaluationReportLoggingListener : 
69
70Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
712021-11-19 09:41:07.970 ERROR 16666 --- [           main] o.s.boot.SpringApplication               : Application run failed
72
73org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null
74        at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.13.jar:5.3.13]
75        at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.13.jar:5.3.13]
76        at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.13.jar:5.3.13]
77        at java.base/java.lang.Iterable.forEach(Iterable.java:75) ~[na:na]
78        at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.13.jar:5.3.13]
79        at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.13.jar:5.3.13]
80        at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.13.jar:5.3.13]
81        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.13.jar:5.3.13]
82        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.0.jar:2.6.0]
83        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.0.jar:2.6.0]
84        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.0.jar:2.6.0]
85        at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.0.jar:2.6.0]
86        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.0.jar:2.6.0]
87        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1290) ~[spring-boot-2.6.0.jar:2.6.0]
88        at com.example.springfox.SpringFoxApplication.main(SpringFoxApplication.java:10) ~[main/:na]
89Caused by: java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null
90        at springfox.documentation.spring.web.WebMvcPatternsRequestConditionWrapper.getPatterns(WebMvcPatternsRequestConditionWrapper.java:56) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
91        at springfox.documentation.RequestHandler.sortedPaths(RequestHandler.java:113) ~[springfox-core-3.0.0.jar:3.0.0]
92        at springfox.documentation.spi.service.contexts.Orderings.lambda$byPatternsCondition$3(Orderings.java:89) ~[springfox-spi-3.0.0.jar:3.0.0]
93        at java.base/java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469) ~[na:na]
94        at java.base/java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) ~[na:na]
95        at java.base/java.util.TimSort.sort(TimSort.java:220) ~[na:na]
96        at java.base/java.util.Arrays.sort(Arrays.java:1306) ~[na:na]
97        at java.base/java.util.ArrayList.sort(ArrayList.java:1721) ~[na:na]
98        at java.base/java.util.stream.SortedOps$RefSortingSink.end(SortedOps.java:392) ~[na:na]
99        at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
100        at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
101        at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
102        at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
103        at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485) ~[na:na]
104        at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
105        at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
106        at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
107        at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na]
108        at springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider.requestHandlers(WebMvcRequestHandlerProvider.java:81) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
109        at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195) ~[na:na]
110        at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) ~[na:na]
111        at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
112        at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
113        at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
114        at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
115        at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na]
116        at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.withDefaults(AbstractDocumentationPluginsBootstrapper.java:107) ~[springfox-spring-web-3.0.0.jar:3.0.0]
117        at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.buildContext(AbstractDocumentationPluginsBootstrapper.java:91) ~[springfox-spring-web-3.0.0.jar:3.0.0]
118        at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.bootstrapDocumentationPlugins(AbstractDocumentationPluginsBootstrapper.java:82) ~[springfox-spring-web-3.0.0.jar:3.0.0]
119        at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:100) ~[springfox-spring-web-3.0.0.jar:3.0.0]
120        at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.13.jar:5.3.13]
121        ... 14 common frames omitted
122
123
124FAILURE: Build failed with an exception.
125
126* What went wrong:
127Execution failed for task ':bootRun'.
128> Process 'command '/home/advance/.sdkman/candidates/java/15.0.2-open/bin/java'' finished with non-zero exit value 1
129
130* Try:
131Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
132
133* Get more help at https://help.gradle.org
134
135Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
136Use '--warning-mode all' to show the individual deprecation warnings.
137See https://docs.gradle.org/6.9.1/userguide/command_line_interface.html#sec:command_line_warnings
138
139BUILD FAILED in 2s
1405 actionable tasks: 5 executed
141

Does anyone have an idea how to solve it?

ANSWER

Answered 2022-Feb-08 at 12:36

This problem's caused by a bug in Springfox. It's making an assumption about how Spring MVC is set up that doesn't always hold true. Specifically, it's assuming that MVC's path matching will use the Ant-based path matcher and not the PathPattern-based matcher. PathPattern-based matching has been an option for some time now and is the default as of Spring Boot 2.6.

As described in Spring Boot 2.6's release notes, you can restore the configuration that Springfox assumes will be used by setting spring.mvc.pathmatch.matching-strategy to ant-path-matcher in your application.properties file. Note that this will only work if you are not using Spring Boot's Actuator. The Actuator always uses PathPattern-based parsing, irrespective of the configured matching-strategy. A change to Springfox will be required if you want to use it with the Actuator in Spring Boot 2.6 and later.

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

QUESTION

Allow insecure protocols, android gradle

Asked 2022-Mar-17 at 10:30

I recently updated my android studio to Arctic Fox and got an error in my project

1A problem occurred configuring root project 'so10'.
2> Could not resolve all dependencies for configuration ':classpath'.
3   > Using insecure protocols with repositories, without explicit opt-in, is     unsupported. Switch Maven repository 
4'maven3(http://oss.sonatype.org/content/repositories/snapshots)' to redirect to a secure protocol (like HTTPS) or allow insecure protocols.
5 See https://docs.gradle.org/7.0.2/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol for more details. 
6

This is my gradle where the problem occurs

1A problem occurred configuring root project 'so10'.
2> Could not resolve all dependencies for configuration ':classpath'.
3   > Using insecure protocols with repositories, without explicit opt-in, is     unsupported. Switch Maven repository 
4'maven3(http://oss.sonatype.org/content/repositories/snapshots)' to redirect to a secure protocol (like HTTPS) or allow insecure protocols.
5 See https://docs.gradle.org/7.0.2/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol for more details. 
6repositories {
7    // maven { url 'https://maven.fabric.io/public' }
8    maven { url "https://jitpack.io" }
9    maven { url 'https://raw.github.com/Raizlabs/maven-releases/master/releases' }
10    maven { url 'http://oss.sonatype.org/content/repositories/snapshots'}
11    maven { url "https://plugins.gradle.org/m2/" }
12    maven { url 'https://maven.google.com'  }
13    google()
14    mavenCentral()
15    jcenter()
16}
17

How do I solve it?

ANSWER

Answered 2022-Mar-17 at 10:30

For insecure HTTP connections in Gradle 7+ versions, we need to specify a boolean allowInsecureProtocol as true to MavenArtifactRepository closure.
Since you have received this error for sonatype repository, you need to set the repositories as below:

  1. Groovy DSL
1A problem occurred configuring root project 'so10'.
2> Could not resolve all dependencies for configuration ':classpath'.
3   > Using insecure protocols with repositories, without explicit opt-in, is     unsupported. Switch Maven repository 
4'maven3(http://oss.sonatype.org/content/repositories/snapshots)' to redirect to a secure protocol (like HTTPS) or allow insecure protocols.
5 See https://docs.gradle.org/7.0.2/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol for more details. 
6repositories {
7    // maven { url 'https://maven.fabric.io/public' }
8    maven { url "https://jitpack.io" }
9    maven { url 'https://raw.github.com/Raizlabs/maven-releases/master/releases' }
10    maven { url 'http://oss.sonatype.org/content/repositories/snapshots'}
11    maven { url "https://plugins.gradle.org/m2/" }
12    maven { url 'https://maven.google.com'  }
13    google()
14    mavenCentral()
15    jcenter()
16}
17repositories {
18    maven {
19        url "http://oss.sonatype.org/content/repositories/snapshots"
20        allowInsecureProtocol = true
21    }
22    // other repositories ...
23}
24
  1. Kotlin DSL
1A problem occurred configuring root project 'so10'.
2> Could not resolve all dependencies for configuration ':classpath'.
3   > Using insecure protocols with repositories, without explicit opt-in, is     unsupported. Switch Maven repository 
4'maven3(http://oss.sonatype.org/content/repositories/snapshots)' to redirect to a secure protocol (like HTTPS) or allow insecure protocols.
5 See https://docs.gradle.org/7.0.2/dsl/org.gradle.api.artifacts.repositories.UrlArtifactRepository.html#org.gradle.api.artifacts.repositories.UrlArtifactRepository:allowInsecureProtocol for more details. 
6repositories {
7    // maven { url 'https://maven.fabric.io/public' }
8    maven { url "https://jitpack.io" }
9    maven { url 'https://raw.github.com/Raizlabs/maven-releases/master/releases' }
10    maven { url 'http://oss.sonatype.org/content/repositories/snapshots'}
11    maven { url "https://plugins.gradle.org/m2/" }
12    maven { url 'https://maven.google.com'  }
13    google()
14    mavenCentral()
15    jcenter()
16}
17repositories {
18    maven {
19        url "http://oss.sonatype.org/content/repositories/snapshots"
20        allowInsecureProtocol = true
21    }
22    // other repositories ...
23}
24repositories {
25    maven {
26        url = uri("http://oss.sonatype.org/content/repositories/snapshots")
27        isAllowInsecureProtocol = true
28    }
29    // other repositories ...
30}
31

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

QUESTION

ASP.NET Core 6 how to access Configuration during startup

Asked 2022-Mar-08 at 11:45

In earlier versions, we had Startup.cs class and we get configuration object as follows in the Startup file.

1public class Startup 
2{
3    private readonly IHostEnvironment environment;
4    private readonly IConfiguration config;
5
6    public Startup(IConfiguration configuration, IHostEnvironment environment) 
7    {
8        this.config = configuration;
9        this.environment = environment;
10    }
11
12    public void ConfigureServices(IServiceCollection services) 
13    {
14        // Add Services
15    }
16
17    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
18    {
19        // Add Middlewares
20    }
21
22}
23

Now in .NET 6 (With Visual Studio 2022), we don't see the Startup.cs class. Looks like its days are numbered. So how do we get these objects like Configuration(IConfiguration) and Hosting Environment(IHostEnvironment)

How do we get these objects, to say read the configuration from appsettings? Currently the Program.cs file looks like this.

1public class Startup 
2{
3    private readonly IHostEnvironment environment;
4    private readonly IConfiguration config;
5
6    public Startup(IConfiguration configuration, IHostEnvironment environment) 
7    {
8        this.config = configuration;
9        this.environment = environment;
10    }
11
12    public void ConfigureServices(IServiceCollection services) 
13    {
14        // Add Services
15    }
16
17    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
18    {
19        // Add Middlewares
20    }
21
22}
23using Festify.Database;
24using Microsoft.EntityFrameworkCore;
25
26var builder = WebApplication.CreateBuilder(args);
27
28// Add services to the container.
29builder.Services.AddRazorPages();
30
31builder.Services.AddDbContext<FestifyContext>();
32
33
34////////////////////////////////////////////////
35// The following is Giving me error as Configuration 
36// object is not avaible, I dont know how to inject this here.
37////////////////////////////////////////////////
38
39
40builder.Services.AddDbContext<FestifyContext>(opt =>
41        opt.UseSqlServer(
42            Configuration.GetConnectionString("Festify")));
43
44
45var app = builder.Build();
46
47// Configure the HTTP request pipeline.
48if (!app.Environment.IsDevelopment())
49{
50    app.UseExceptionHandler("/Error");
51    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
52    app.UseHsts();
53}
54
55app.UseHttpsRedirection();
56app.UseStaticFiles();
57
58app.UseRouting();
59
60app.UseAuthorization();
61
62app.MapRazorPages();
63
64app.Run();
65

I want to know how to read the configuration from appsettings.json ?

ANSWER

Answered 2021-Oct-26 at 12:26

WebApplicationBuilder returned by WebApplication.CreateBuilder(args) exposes Configuration and Environment properties:

1public class Startup 
2{
3    private readonly IHostEnvironment environment;
4    private readonly IConfiguration config;
5
6    public Startup(IConfiguration configuration, IHostEnvironment environment) 
7    {
8        this.config = configuration;
9        this.environment = environment;
10    }
11
12    public void ConfigureServices(IServiceCollection services) 
13    {
14        // Add Services
15    }
16
17    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
18    {
19        // Add Middlewares
20    }
21
22}
23using Festify.Database;
24using Microsoft.EntityFrameworkCore;
25
26var builder = WebApplication.CreateBuilder(args);
27
28// Add services to the container.
29builder.Services.AddRazorPages();
30
31builder.Services.AddDbContext<FestifyContext>();
32
33
34////////////////////////////////////////////////
35// The following is Giving me error as Configuration 
36// object is not avaible, I dont know how to inject this here.
37////////////////////////////////////////////////
38
39
40builder.Services.AddDbContext<FestifyContext>(opt =>
41        opt.UseSqlServer(
42            Configuration.GetConnectionString("Festify")));
43
44
45var app = builder.Build();
46
47// Configure the HTTP request pipeline.
48if (!app.Environment.IsDevelopment())
49{
50    app.UseExceptionHandler("/Error");
51    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
52    app.UseHsts();
53}
54
55app.UseHttpsRedirection();
56app.UseStaticFiles();
57
58app.UseRouting();
59
60app.UseAuthorization();
61
62app.MapRazorPages();
63
64app.Run();
65var builder = WebApplication.CreateBuilder(args);
66
67// Add services to the container.
68...
69ConfigurationManager configuration = builder.Configuration;
70IWebHostEnvironment environment = builder.Environment;
71

WebApplication returned by WebApplicationBuilder.Build() also exposes Configuration and Environment:

1public class Startup 
2{
3    private readonly IHostEnvironment environment;
4    private readonly IConfiguration config;
5
6    public Startup(IConfiguration configuration, IHostEnvironment environment) 
7    {
8        this.config = configuration;
9        this.environment = environment;
10    }
11
12    public void ConfigureServices(IServiceCollection services) 
13    {
14        // Add Services
15    }
16
17    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
18    {
19        // Add Middlewares
20    }
21
22}
23using Festify.Database;
24using Microsoft.EntityFrameworkCore;
25
26var builder = WebApplication.CreateBuilder(args);
27
28// Add services to the container.
29builder.Services.AddRazorPages();
30
31builder.Services.AddDbContext<FestifyContext>();
32
33
34////////////////////////////////////////////////
35// The following is Giving me error as Configuration 
36// object is not avaible, I dont know how to inject this here.
37////////////////////////////////////////////////
38
39
40builder.Services.AddDbContext<FestifyContext>(opt =>
41        opt.UseSqlServer(
42            Configuration.GetConnectionString("Festify")));
43
44
45var app = builder.Build();
46
47// Configure the HTTP request pipeline.
48if (!app.Environment.IsDevelopment())
49{
50    app.UseExceptionHandler("/Error");
51    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
52    app.UseHsts();
53}
54
55app.UseHttpsRedirection();
56app.UseStaticFiles();
57
58app.UseRouting();
59
60app.UseAuthorization();
61
62app.MapRazorPages();
63
64app.Run();
65var builder = WebApplication.CreateBuilder(args);
66
67// Add services to the container.
68...
69ConfigurationManager configuration = builder.Configuration;
70IWebHostEnvironment environment = builder.Environment;
71var app = builder.Build();
72IConfiguration configuration = app.Configuration;
73IWebHostEnvironment environment = app.Environment;
74

Also check the migration guide and code samples.

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

QUESTION

throwError(error) is now deprecated, but there is no new Error(HttpErrorResponse)

Asked 2022-Mar-01 at 00:42

Apparently throwError(error) is now deprecated. The IntelliSense of VS Code suggests throwError(() => new Error('error'). new Error(...) accepts only strings. What's the correct way to replace it without breaking my HttpErrorHandlerService ?

http-error.interceptor.ts
1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest<any>,
46    next: HttpHandler
47  ): Observable<HttpEvent<any>> {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse && error.error && error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150
auth.interceptor.ts
1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest<any>,
46    next: HttpHandler
47  ): Observable<HttpEvent<any>> {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse && error.error && error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject<AuthResponse | null>(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest<any>,
202    next: HttpHandler
203  ): Observable<HttpEvent<any>> {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &&
208      error.status === 401 &&
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) => {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() => new Error("RefreshTokenFailed"));
234        }),
235        catchError((error) => {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() => (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) => result !== null),
245        take(1),
246        switchMap(() => next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252

ANSWER

Answered 2021-Aug-04 at 19:08

Instead of this:

1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest<any>,
46    next: HttpHandler
47  ): Observable<HttpEvent<any>> {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse && error.error && error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject<AuthResponse | null>(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest<any>,
202    next: HttpHandler
203  ): Observable<HttpEvent<any>> {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &&
208      error.status === 401 &&
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) => {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() => new Error("RefreshTokenFailed"));
234        }),
235        catchError((error) => {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() => (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) => result !== null),
245        take(1),
246        switchMap(() => next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252    catchError((error) => {
253      this.authService.signOut();
254      return throwError(error);
255    }),
256

You could try this:

1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest<any>,
46    next: HttpHandler
47  ): Observable<HttpEvent<any>> {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse && error.error && error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject<AuthResponse | null>(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest<any>,
202    next: HttpHandler
203  ): Observable<HttpEvent<any>> {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &&
208      error.status === 401 &&
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) => {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() => new Error("RefreshTokenFailed"));
234        }),
235        catchError((error) => {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() => (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) => result !== null),
245        take(1),
246        switchMap(() => next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252    catchError((error) => {
253      this.authService.signOut();
254      return throwError(error);
255    }),
256    catchError((error) => {
257      this.authService.signOut();
258      return throwError(() => error);
259    }),
260

I wasn't able to test it thoroughly, but a simple attempt seemed to work.

This was my simple test (using RxJS v7.2):

Service

1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest<any>,
46    next: HttpHandler
47  ): Observable<HttpEvent<any>> {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse && error.error && error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject<AuthResponse | null>(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest<any>,
202    next: HttpHandler
203  ): Observable<HttpEvent<any>> {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &&
208      error.status === 401 &&
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) => {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() => new Error("RefreshTokenFailed"));
234        }),
235        catchError((error) => {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() => (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) => result !== null),
245        take(1),
246        switchMap(() => next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252    catchError((error) => {
253      this.authService.signOut();
254      return throwError(error);
255    }),
256    catchError((error) => {
257      this.authService.signOut();
258      return throwError(() => error);
259    }),
260  getProducts(): Observable<IProduct[]> {
261    return this.http.get<IProduct[]>(this.productUrl)
262      .pipe(
263        tap(data => console.log('All: ', JSON.stringify(data))),
264        catchError(this.handleError)
265      );
266  }
267
268  private handleError(err: HttpErrorResponse): Observable<never> {
269    // just a test ... more could would go here
270    return throwError(() => err);
271  }
272

Notice that err here is of type HttpErrorResponse.

Component

1import { Injectable } from '@angular/core';
2import {
3  HttpEvent,
4  HttpInterceptor,
5  HttpHandler,
6  HttpRequest,
7  HttpErrorResponse,
8  HttpResponse,
9  HttpHeaders
10} from '@angular/common/http';
11import { Observable, EMPTY, finalize, catchError, timeout, map, throwError } from 'rxjs';
12
13import { HttpErrorHandlerService } from '@core/services';
14
15@Injectable()
16export class HttpErrorInterceptor implements HttpInterceptor {
17  private readonly APP_XHR_TIMEOUT = 6000;
18
19  constructor(private errorHandlerService: HttpErrorHandlerService) {}
20
21  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
22    return next.handle(this.performRequest(request)).pipe(
23      timeout(this.APP_XHR_TIMEOUT),
24      map((event: HttpEvent<any>) => this.handleSuccessfulResponse(event)),
25      catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next)),
26      finalize(this.handleRequestCompleted.bind(this))
27    );
28  }
29
30  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
31    let headers: HttpHeaders = request.headers;
32    //headers = headers.set('MyCustomHeaderKey', `MyCustomHeaderValue`);
33    return request.clone({ headers });
34  }
35
36  private handleSuccessfulResponse(event: HttpEvent<any>): HttpEvent<any> {
37    if (event instanceof HttpResponse) {
38      event = event.clone({ body: event.body.response });
39    }
40    return event;
41  }
42
43  private processRequestError(
44    error: HttpErrorResponse,
45    request: HttpRequest<any>,
46    next: HttpHandler
47  ): Observable<HttpEvent<any>> {
48    console.log('http error response');
49
50    if ([401].includes(error.status)) {
51      return throwError(error);
52    }
53
54    this.errorHandlerService.handle(error);
55
56    return throwError(error);
57  }
58
59  private handleRequestCompleted(): void {
60    // console.log(`Request finished`);
61  }
62}
63
64import { Injectable } from '@angular/core';
65import { HttpErrorResponse } from '@angular/common/http';
66
67import { MessageService } from 'primeng/api';
68import { TimeoutError } from 'rxjs';
69
70/**
71 * Shows a user-friendly error message when a HTTP request fails.
72 */
73@Injectable({
74  providedIn: 'root'
75})
76export class HttpErrorHandlerService {
77  constructor(private messageService: MessageService) {}
78
79  handle(error: Error | HttpErrorResponse) {
80    if (error instanceof TimeoutError) {
81      return this.openDialog('error', `Няма връзка до сървъра.`);
82    }
83
84    if (error instanceof HttpErrorResponse && error.error && error.error.message) {
85      return this.openDialog('error', error.error.message);
86    }
87
88    if (error instanceof Error) {
89      switch (error.message) {
90        default:
91          return this.openDialog('error', `An unknown error occurred`);
92      }
93    }
94
95    // Generic HTTP errors
96    switch (error.status) {
97      case 400:
98        switch (error.error) {
99          case 'invalid_username_or_password':
100            return this.openDialog('error', 'Невалидно потребителско име или парола');
101          default:
102            return this.openDialog('error', 'Bad request');
103        }
104
105      case 401:
106        return this.openDialog('error', 'Ще трябва да се логнете отново');
107
108      case 403:
109        return this.openDialog('error', `You don't have the required permissions`);
110
111      case 404:
112        return this.openDialog('error', 'Resource not found');
113
114      case 422:
115        return this.openDialog('error', 'Invalid data provided');
116
117      case 500:
118      case 501:
119      case 502:
120      case 503:
121        return this.openDialog('error', 'An internal server error occurred');
122
123      case -1:
124        return this.openDialog(
125          'error',
126          'You appear to be offline. Please check your internet connection and try again.'
127        );
128
129      case 0:
130        return this.openDialog('error', `CORS issue?`);
131
132      default:
133        return this.openDialog('error', `An unknown error occurred`);
134    }
135  }
136
137  private openDialog(severity: string, message: string) {
138    if (message?.trim()) {
139      this.messageService.add({
140        key: 'interceptor',
141        severity: severity,
142        summary: 'Информация',
143        detail: message,
144        life: 3000
145      });
146    }
147  }
148}
149
150import { Injectable } from '@angular/core';
151import {
152  HttpRequest,
153  HttpHandler,
154  HttpEvent,
155  HttpInterceptor,
156  HttpErrorResponse
157} from '@angular/common/http';
158import {
159  BehaviorSubject,
160  catchError,
161  EMPTY,
162  filter,
163  finalize,
164  Observable,
165  switchMap,
166  take,
167  throwError
168} from 'rxjs';
169
170import { AuthService } from '@core/services';
171import { AuthResponse } from '@core/types';
172
173@Injectable()
174export class AuthInterceptor implements HttpInterceptor {
175  private refreshTokenInProgress: boolean;
176  private refreshToken$ = new BehaviorSubject<AuthResponse | null>(null);
177
178  constructor(private authService: AuthService) {}
179
180  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
181    return next
182      .handle(this.performRequest(request))
183      .pipe(
184        catchError((error: HttpErrorResponse) => this.processRequestError(error, request, next))
185      );
186  }
187
188  private performRequest(request: HttpRequest<any>): HttpRequest<any> {
189    const accessToken = this.authService.getAccessToken();
190
191    let headers = request.headers;
192    if (accessToken) {
193      headers = headers.set('Authorization', `Bearer ${accessToken}`);
194    }
195
196    return request.clone({ headers });
197  }
198
199  private processRequestError(
200    error: HttpErrorResponse,
201    request: HttpRequest<any>,
202    next: HttpHandler
203  ): Observable<HttpEvent<any>> {
204    console.log('auth interceptor called');
205
206    if (
207      error instanceof HttpErrorResponse &&
208      error.status === 401 &&
209      this.authService.isSignedIn()
210    ) {
211      return this.refreshToken(request, next);
212    }
213
214    return throwError(error);
215  }
216
217  private refreshToken(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
218    console.log('refresh token in auth.interceptor called');
219
220    // in case the page consists of more than one requests
221    if (!this.refreshTokenInProgress) {
222      this.refreshToken$.next(null);
223      this.refreshTokenInProgress = true;
224
225      return this.authService.refreshToken().pipe(
226        switchMap((response) => {
227          if (response) {
228            this.refreshToken$.next(response);
229            return next.handle(this.performRequest(request));
230          }
231
232          this.authService.signOut();
233          return throwError(() => new Error("RefreshTokenFailed"));
234        }),
235        catchError((error) => {
236          this.authService.signOut();
237          return throwError(error);
238        }),
239        finalize(() => (this.refreshTokenInProgress = false))
240      );
241    } else {
242      // wait while getting new token
243      return this.refreshToken$.pipe(
244        filter((result) => result !== null),
245        take(1),
246        switchMap(() => next.handle(this.performRequest(request)))
247      );
248    }
249  }
250}
251
252    catchError((error) => {
253      this.authService.signOut();
254      return throwError(error);
255    }),
256    catchError((error) => {
257      this.authService.signOut();
258      return throwError(() => error);
259    }),
260  getProducts(): Observable<IProduct[]> {
261    return this.http.get<IProduct[]>(this.productUrl)
262      .pipe(
263        tap(data => console.log('All: ', JSON.stringify(data))),
264        catchError(this.handleError)
265      );
266  }
267
268  private handleError(err: HttpErrorResponse): Observable<never> {
269    // just a test ... more could would go here
270    return throwError(() => err);
271  }
272  ngOnInit(): void {
273    this.sub = this.productService.getProducts().subscribe({
274      next: products => {
275        this.products = products;
276        this.filteredProducts = this.products;
277      },
278      error: err => this.errorMessage = err.message
279    });
280  }
281

Here I was able to retrieve the message property from the error response and display it in my UI.

Let me know if this works for you.

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

QUESTION

How to use appsettings.json in Asp.net core 6 Program.cs file

Asked 2022-Feb-25 at 21:39

I'm trying to access appsettings.json in my Asp.net core v6 application Program.cs file, but in this version of .Net the Startup class and Program class are merged together and the using and another statements are simplified and removed from Program.cs. In this situation, How to access IConfiguration or how to use dependency injection for example ?

Edited : Here is my default Program.cs that Asp.net 6 created for me

1var builder = WebApplication.CreateBuilder(args);
2// Add services to the container.
3builder.Services.AddControllers();
4builder.Services.AddStackExchangeRedisCache(options =>
5{
6    options.Configuration = "localhost:6379";
7});
8
9builder.Services.AddSwaggerGen(c =>
10{
11    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
12});
13var app = builder.Build();
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16{
17    app.UseSwagger();
18    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
19}
20app.UseHttpsRedirection();
21app.UseAuthorization();
22app.MapControllers();
23app.Run();
24

For example , I want to use appsettings.json instead of hard typed connectionstring in this line :

1var builder = WebApplication.CreateBuilder(args);
2// Add services to the container.
3builder.Services.AddControllers();
4builder.Services.AddStackExchangeRedisCache(options =>
5{
6    options.Configuration = "localhost:6379";
7});
8
9builder.Services.AddSwaggerGen(c =>
10{
11    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
12});
13var app = builder.Build();
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16{
17    app.UseSwagger();
18    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
19}
20app.UseHttpsRedirection();
21app.UseAuthorization();
22app.MapControllers();
23app.Run();
24options.Configuration = "localhost:6379";
25

ANSWER

Answered 2021-Sep-30 at 11:13

Assuming an appsettings.json

1var builder = WebApplication.CreateBuilder(args);
2// Add services to the container.
3builder.Services.AddControllers();
4builder.Services.AddStackExchangeRedisCache(options =>
5{
6    options.Configuration = "localhost:6379";
7});
8
9builder.Services.AddSwaggerGen(c =>
10{
11    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
12});
13var app = builder.Build();
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16{
17    app.UseSwagger();
18    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
19}
20app.UseHttpsRedirection();
21app.UseAuthorization();
22app.MapControllers();
23app.Run();
24options.Configuration = "localhost:6379";
25{
26    "RedisCacheOptions" : {
27        "Configuration": "localhost:6379"
28    }
29}
30

There is nothing stopping you from building a configuration object to extract the desired settings.

1var builder = WebApplication.CreateBuilder(args);
2// Add services to the container.
3builder.Services.AddControllers();
4builder.Services.AddStackExchangeRedisCache(options =>
5{
6    options.Configuration = "localhost:6379";
7});
8
9builder.Services.AddSwaggerGen(c =>
10{
11    c.SwaggerDoc("v1", new() { Title = "BasketAPI", Version = "v1" });
12});
13var app = builder.Build();
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16{
17    app.UseSwagger();
18    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BasketAPI v1"));
19}
20app.UseHttpsRedirection();
21app.UseAuthorization();
22app.MapControllers();
23app.Run();
24options.Configuration = "localhost:6379";
25{
26    "RedisCacheOptions" : {
27        "Configuration": "localhost:6379"
28    }
29}
30IConfiguration configuration = new ConfigurationBuilder()
31                            .AddJsonFile("appsettings.json")
32                            .Build();
33
34var builder = WebApplication.CreateBuilder(args);
35// Add services to the container.
36builder.Services.AddControllers();
37builder.Services.AddStackExchangeRedisCache(options => {
38    options.Configuration = configuration["RedisCacheOptions:Configuration"];
39});
40
41//...
42

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

QUESTION

android:exported needs to be explicitly specified for <activity>. Apps targeting Android 12 and higher are required to specify

Asked 2022-Feb-23 at 14:13

After upgrading to android 12, the application is not compiling. It shows

"Manifest merger failed with multiple errors, see logs"

Error showing in Merged manifest:

Merging Errors: Error: android:exported needs to be explicitly specified for . Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details. main manifest (this file)

I have set all the activity with android:exported="false". But it is still showing this issue.

My manifest file:

1<?xml version="1.0" encoding="utf-8"?>
2<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3    xmlns:tools="http://schemas.android.com/tools"
4    package="eu.siacs.conversations">
5
6    <uses-sdk tools:overrideLibrary="net.ypresto.androidtranscoder" />
7
8    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
9    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
10    <uses-permission android:name="android.permission.READ_CONTACTS" />
11    <uses-permission android:name="android.permission.READ_PROFILE" />
12    <uses-permission
13        android:name="android.permission.READ_PHONE_STATE"
14        android:maxSdkVersion="22" />
15    <uses-permission android:name="android.permission.INTERNET" />
16    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
17    <uses-permission android:name="android.permission.WAKE_LOCK" />
18    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
19    <uses-permission android:name="android.permission.VIBRATE" />
20    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
21    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
22    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
23    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
24    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
25    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
26
27    <uses-feature
28        android:name="android.hardware.location"
29        android:required="false" />
30    <uses-feature
31        android:name="android.hardware.location.gps"
32        android:required="false" />
33    <uses-feature
34        android:name="android.hardware.location.network"
35        android:required="false" />
36
37    <uses-permission android:name="android.permission.CAMERA" />
38    <uses-permission android:name="android.permission.RECORD_AUDIO" />
39    <uses-permission android:name="android.permission.BLUETOOTH" />
40    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
41    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
42    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
43
44    <uses-feature
45        android:name="android.hardware.camera"
46        android:required="false" />
47    <uses-feature
48        android:name="android.hardware.camera.autofocus"
49        android:required="false" />
50    <uses-feature
51        android:name="android.hardware.microphone"
52        android:required="false" />
53
54    <application
55        android:name=".Application"
56        android:allowBackup="false"
57        android:allowClearUserData="true"
58        android:appCategory="social"
59        android:hardwareAccelerated="true"
60        android:icon="@mipmap/ic_app_launch"
61        android:label="@string/app_name"
62        android:largeHeap="true"
63        android:networkSecurityConfig="@xml/network_security_configuration"
64        android:requestLegacyExternalStorage="true"
65        android:roundIcon="@mipmap/ic_app_launch_round"
66        android:theme="@style/ConversationsTheme"
67        android:usesCleartextTraffic="true"
68        android:windowSoftInputMode="adjustPan|adjustResize"
69        tools:replace="android:label"
70        tools:targetApi="q">
71        <activity
72            android:name=".ui.search.GroupSearchActivity"
73            android:exported="true" />
74        <activity
75            android:name=".ui.profileUpdating.FavouritesActivity"
76            android:exported="true" />
77        <activity
78            android:name=".ui.profileUpdating.NameActivity"
79            android:exported="true" />
80        <activity
81            android:name=".ui.CompulsoryUpdateActivity"
82            android:exported="true" />
83        <activity android:name=".ui.payments.doPayment.DoPaymentActivity"
84            android:exported="true" />
85        <activity android:name=".ui.individualList.IndividualListActivity"
86            android:exported="true" />
87        <activity android:name=".ui.payments.setPayment.SetPaymentActivity"
88            android:exported="true" />
89        <activity android:name=".ui.login.otpActivity.OTPActivity"
90            android:exported="true" />
91        <activity android:name=".ui.login.loginActivity.LoginActivity"
92            android:exported="true" />
93
94        <service android:name=".services.XmppConnectionService" android:exported="true" />
95
96        <receiver android:name=".services.EventReceiver"
97            android:exported="true">
98            <intent-filter>
99                <action android:name="android.intent.action.BOOT_COMPLETED" />
100                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
101                <action android:name="android.intent.action.ACTION_SHUTDOWN" />
102                <action android:name="android.media.RINGER_MODE_CHANGED" />
103            </intent-filter>
104        </receiver>
105
106        <activity
107            android:name=".ui.ShareLocationActivity"
108            android:label="@string/title_activity_share_location"
109            android:exported="true"/>
110        <activity
111            android:name=".ui.SearchActivity"
112            android:label="@string/search_messages"
113            android:exported="true" />
114        <activity
115            android:name=".ui.RecordingActivity"
116            android:configChanges="orientation|screenSize"
117            android:theme="@style/ConversationsTheme.Dialog"
118            android:exported="true" />
119        <activity
120            android:name=".ui.ShowLocationActivity"
121            android:label="@string/title_activity_show_location"
122            android:exported="true" />
123        <activity
124            android:name=".ui.SplashActivity"
125            android:theme="@style/SplashTheme"
126            android:exported="true">
127            <intent-filter>
128                <action android:name="android.intent.action.MAIN" />
129
130                <category android:name="android.intent.category.LAUNCHER" />
131            </intent-filter>
132        </activity>
133        <activity
134            android:name=".ui.ConversationsActivity"
135            android:label="@string/app_name"
136            android:launchMode="singleTask"
137            android:minWidth="300dp"
138            android:minHeight="300dp"
139            android:exported="true"
140            android:windowSoftInputMode="stateHidden" />
141        <activity
142            android:name=".ui.ScanActivity"
143            android:screenOrientation="portrait"
144            android:exported="true"
145            android:theme="@style/ConversationsTheme.FullScreen"
146            android:windowSoftInputMode="stateAlwaysHidden" />
147        <activity
148            android:name=".ui.UriHandlerActivity"
149            android:label="@string/app_name"
150            android:exported="true">
151            <intent-filter>
152                <action android:name="android.intent.action.VIEW" />
153
154                <category android:name="android.intent.category.DEFAULT" />
155                <category android:name="android.intent.category.BROWSABLE" />
156
157                <data android:scheme="xmpp" />
158            </intent-filter>
159            <intent-filter android:autoVerify="true">
160                <action android:name="android.intent.action.VIEW" />
161
162                <category android:name="android.intent.category.DEFAULT" />
163                <category android:name="android.intent.category.BROWSABLE" />
164
165                <data android:scheme="https" />
166                <data android:host="im.app.in" />
167                <data android:pathPrefix="/i/" />
168                <data android:pathPrefix="/j/" />
169            </intent-filter>
170            <intent-filter>
171                <action android:name="android.intent.action.SENDTO" />
172
173                <category android:name="android.intent.category.DEFAULT" />
174
175                <data android:scheme="imto" />
176                <data android:host="jabber" />
177            </intent-filter>
178        </activity>
179        <activity
180            android:name=".ui.StartConversationActivity"
181            android:label="@string/title_activity_start_conversation"
182            android:launchMode="singleTop"
183            android:exported="true">
184            <intent-filter>
185                <action android:name="android.intent.action.VIEW" />
186            </intent-filter>
187        </activity>
188        <activity
189            android:name=".ui.SettingsActivity"
190            android:label="@string/title_activity_settings"
191            android:exported="true">
192            <intent-filter>
193                <action android:name="android.intent.action.MAIN" />
194
195                <category android:name="android.intent.category.NOTIFICATION_PREFERENCES" />
196            </intent-filter>
197        </activity>
198        <activity
199            android:name=".ui.ChooseContactActivity"
200            android:label="@string/title_activity_choose_contact"
201            android:exported="true" />
202        <activity
203            android:name=".ui.BlocklistActivity"
204            android:label="@string/title_activity_block_list"
205            android:exported="true"/>
206        <activity
207            android:name=".ui.ChangePasswordActivity"
208            android:label="@string/change_password_on_server"
209            android:exported="true"/>
210        <activity
211            android:name=".ui.ChooseAccountForProfilePictureActivity"
212            android:enabled="false"
213            android:label="@string/choose_account"
214            android:exported="true">
215            <intent-filter android:label="@string/set_profile_picture">
216                <action android:name="android.intent.action.ATTACH_DATA" />
217
218                <category android:name="android.intent.category.DEFAULT" />
219
220                <data android:mimeType="image/*" />
221            </intent-filter>
222        </activity>
223        <activity
224            android:name=".ui.ShareViaAccountActivity"
225            android:label="@string/title_activity_share_via_account"
226            android:launchMode="singleTop"
227            android:exported="true" />
228        <activity
229            android:name=".ui.EditAccountActivity"
230            android:launchMode="singleTop"
231            android:exported="true"
232            android:windowSoftInputMode="stateHidden|adjustResize" />
233        <activity
234            android:name=".ui.ConferenceDetailsActivity"
235            android:label="@string/action_muc_details"
236            android:exported="true"
237            android:windowSoftInputMode="stateHidden" />
238        <activity
239            android:name=".ui.ContactDetailsActivity"
240            android:exported="true"
241            android:windowSoftInputMode="stateHidden" />
242        <activity
243            android:name=".ui.PublishProfilePictureActivity"
244            android:label="@string/mgmt_account_publish_avatar"
245            android:exported="true"
246            android:windowSoftInputMode="stateHidden" />
247        <activity
248            android:name=".ui.PublishGroupChatProfilePictureActivity"
249            android:exported="true"
250            android:label="@string/group_chat_avatar" />
251        <activity
252            android:name=".ui.ShareWithActivity"
253            android:label="@string/app_name"
254            android:launchMode="singleTop"
255            android:exported="true">
256            <intent-filter>
257                <action android:name="android.intent.action.SEND" />
258                <action android:name="android.intent.action.SEND_MULTIPLE" />
259
260                <category android:name="android.intent.category.DEFAULT" />
261
262                <data android:mimeType="text/plain" />
263            </intent-filter>
264            <intent-filter>
265                <action android:name="android.intent.action.SEND" />
266                <action android:name="android.intent.action.SEND_MULTIPLE" />
267
268                <category android:name="android.intent.category.DEFAULT" />
269
270                <data android:mimeType="*/*" />
271            </intent-filter>
272
273            <!-- the value here needs to be the full class name; independent of the configured applicationId -->
274            <meta-data
275                android:name="android.service.chooser.chooser_target_service"
276                android:value="eu.siacs.conversations.services.ContactChooserTargetService" />
277        </activity>
278        <activity
279            android:name=".ui.TrustKeysActivity"
280            android:label="@string/trust_omemo_fingerprints"
281            android:exported="true"
282            android:windowSoftInputMode="stateAlwaysHidden" />
283        <activity
284            android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
285            android:exported="true"
286            android:theme="@style/Base.Theme.AppCompat" />
287        <activity android:name=".ui.MemorizingActivity"
288            android:exported="true" />
289        <activity
290            android:name=".ui.MediaBrowserActivity"
291            android:exported="true"
292            android:label="@string/media_browser" />
293
294        <service android:name=".services.ExportBackupService" android:exported="true"/>
295        <service android:name=".services.ImportBackupService" android:exported="true"/>
296        <service
297            android:name=".services.ContactChooserTargetService"
298            android:permission="android.permission.BIND_CHOOSER_TARGET_SERVICE"
299            android:exported="true">
300            <intent-filter>
301                <action android:name="android.service.chooser.ChooserTargetService" />
302            </intent-filter>
303        </service>
304        <service android:name=".services.CompulsoryUpdateService" android:exported="true"/>
305
306        <provider
307            android:name="androidx.core.content.FileProvider"
308            android:authorities="${applicationId}.files"
309            android:exported="false"
310            android:grantUriPermissions="true">
311            <meta-data
312                android:name="android.support.FILE_PROVIDER_PATHS"
313                android:resource="@xml/file_paths" />
314        </provider>
315        <provider
316            android:name=".services.BarcodeProvider"
317            android:authorities="${applicationId}.barcodes"
318            android:exported="false"
319            android:grantUriPermissions="true" />
320
321        <activity
322            android:name=".ui.ShortcutActivity"
323            android:label="@string/contact"
324            android:exported="true">
325            <intent-filter>
326                <action android:name="android.intent.action.CREATE_SHORTCUT" />
327            </intent-filter>
328        </activity>
329        <activity
330            android:name=".ui.MucUsersActivity"
331            android:exported="true"
332            android:label="@string/group_chat_members" />
333        <activity
334            android:name=".ui.ChannelDiscoveryActivity"
335            android:exported="true"
336            android:label="@string/discover_channels" />
337        <activity
338            android:name=".ui.RtpSessionActivity"
339            android:autoRemoveFromRecents="true"
340            android:exported="true"
341            android:launchMode="singleInstance"
342            android:supportsPictureInPicture="true" />
343    </application>
344
345</manifest>
346

My second manifest file:

1<?xml version="1.0" encoding="utf-8"?>
2<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3    xmlns:tools="http://schemas.android.com/tools"
4    package="eu.siacs.conversations">
5
6    <uses-sdk tools:overrideLibrary="net.ypresto.androidtranscoder" />
7
8    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
9    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
10    <uses-permission android:name="android.permission.READ_CONTACTS" />
11    <uses-permission android:name="android.permission.READ_PROFILE" />
12    <uses-permission
13        android:name="android.permission.READ_PHONE_STATE"
14        android:maxSdkVersion="22" />
15    <uses-permission android:name="android.permission.INTERNET" />
16    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
17    <uses-permission android:name="android.permission.WAKE_LOCK" />
18    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
19    <uses-permission android:name="android.permission.VIBRATE" />
20    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
21    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
22    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
23    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
24    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
25    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
26
27    <uses-feature
28        android:name="android.hardware.location"
29        android:required="false" />
30    <uses-feature
31        android:name="android.hardware.location.gps"
32        android:required="false" />
33    <uses-feature
34        android:name="android.hardware.location.network"
35        android:required="false" />
36
37    <uses-permission android:name="android.permission.CAMERA" />
38    <uses-permission android:name="android.permission.RECORD_AUDIO" />
39    <uses-permission android:name="android.permission.BLUETOOTH" />
40    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
41    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
42    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
43
44    <uses-feature
45        android:name="android.hardware.camera"
46        android:required="false" />
47    <uses-feature
48        android:name="android.hardware.camera.autofocus"
49        android:required="false" />
50    <uses-feature
51        android:name="android.hardware.microphone"
52        android:required="false" />
53
54    <application
55        android:name=".Application"
56        android:allowBackup="false"
57        android:allowClearUserData="true"
58        android:appCategory="social"
59        android:hardwareAccelerated="true"
60        android:icon="@mipmap/ic_app_launch"
61        android:label="@string/app_name"
62        android:largeHeap="true"
63        android:networkSecurityConfig="@xml/network_security_configuration"
64        android:requestLegacyExternalStorage="true"
65        android:roundIcon="@mipmap/ic_app_launch_round"
66        android:theme="@style/ConversationsTheme"
67        android:usesCleartextTraffic="true"
68        android:windowSoftInputMode="adjustPan|adjustResize"
69        tools:replace="android:label"
70        tools:targetApi="q">
71        <activity
72            android:name=".ui.search.GroupSearchActivity"
73            android:exported="true" />
74        <activity
75            android:name=".ui.profileUpdating.FavouritesActivity"
76            android:exported="true" />
77        <activity
78            android:name=".ui.profileUpdating.NameActivity"
79            android:exported="true" />
80        <activity
81            android:name=".ui.CompulsoryUpdateActivity"
82            android:exported="true" />
83        <activity android:name=".ui.payments.doPayment.DoPaymentActivity"
84            android:exported="true" />
85        <activity android:name=".ui.individualList.IndividualListActivity"
86            android:exported="true" />
87        <activity android:name=".ui.payments.setPayment.SetPaymentActivity"
88            android:exported="true" />
89        <activity android:name=".ui.login.otpActivity.OTPActivity"
90            android:exported="true" />
91        <activity android:name=".ui.login.loginActivity.LoginActivity"
92            android:exported="true" />
93
94        <service android:name=".services.XmppConnectionService" android:exported="true" />
95
96        <receiver android:name=".services.EventReceiver"
97            android:exported="true">
98            <intent-filter>
99                <action android:name="android.intent.action.BOOT_COMPLETED" />
100                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
101                <action android:name="android.intent.action.ACTION_SHUTDOWN" />
102                <action android:name="android.media.RINGER_MODE_CHANGED" />
103            </intent-filter>
104        </receiver>
105
106        <activity
107            android:name=".ui.ShareLocationActivity"
108            android:label="@string/title_activity_share_location"
109            android:exported="true"/>
110        <activity
111            android:name=".ui.SearchActivity"
112            android:label="@string/search_messages"
113            android:exported="true" />
114        <activity
115            android:name=".ui.RecordingActivity"
116            android:configChanges="orientation|screenSize"
117            android:theme="@style/ConversationsTheme.Dialog"
118            android:exported="true" />
119        <activity
120            android:name=".ui.ShowLocationActivity"
121            android:label="@string/title_activity_show_location"
122            android:exported="true" />
123        <activity
124            android:name=".ui.SplashActivity"
125            android:theme="@style/SplashTheme"
126            android:exported="true">
127            <intent-filter>
128                <action android:name="android.intent.action.MAIN" />
129
130                <category android:name="android.intent.category.LAUNCHER" />
131            </intent-filter>
132        </activity>
133        <activity
134            android:name=".ui.ConversationsActivity"
135            android:label="@string/app_name"
136            android:launchMode="singleTask"
137            android:minWidth="300dp"
138            android:minHeight="300dp"
139            android:exported="true"
140            android:windowSoftInputMode="stateHidden" />
141        <activity
142            android:name=".ui.ScanActivity"
143            android:screenOrientation="portrait"
144            android:exported="true"
145            android:theme="@style/ConversationsTheme.FullScreen"
146            android:windowSoftInputMode="stateAlwaysHidden" />
147        <activity
148            android:name=".ui.UriHandlerActivity"
149            android:label="@string/app_name"
150            android:exported="true">
151            <intent-filter>
152                <action android:name="android.intent.action.VIEW" />
153
154                <category android:name="android.intent.category.DEFAULT" />
155                <category android:name="android.intent.category.BROWSABLE" />
156
157                <data android:scheme="xmpp" />
158            </intent-filter>
159            <intent-filter android:autoVerify="true">
160                <action android:name="android.intent.action.VIEW" />
161
162                <category android:name="android.intent.category.DEFAULT" />
163                <category android:name="android.intent.category.BROWSABLE" />
164
165                <data android:scheme="https" />
166                <data android:host="im.app.in" />
167                <data android:pathPrefix="/i/" />
168                <data android:pathPrefix="/j/" />
169            </intent-filter>
170            <intent-filter>
171                <action android:name="android.intent.action.SENDTO" />
172
173                <category android:name="android.intent.category.DEFAULT" />
174
175                <data android:scheme="imto" />
176                <data android:host="jabber" />
177            </intent-filter>
178        </activity>
179        <activity
180            android:name=".ui.StartConversationActivity"
181            android:label="@string/title_activity_start_conversation"
182            android:launchMode="singleTop"
183            android:exported="true">
184            <intent-filter>
185                <action android:name="android.intent.action.VIEW" />
186            </intent-filter>
187        </activity>
188        <activity
189            android:name=".ui.SettingsActivity"
190            android:label="@string/title_activity_settings"
191            android:exported="true">
192            <intent-filter>
193                <action android:name="android.intent.action.MAIN" />
194
195                <category android:name="android.intent.category.NOTIFICATION_PREFERENCES" />
196            </intent-filter>
197        </activity>
198        <activity
199            android:name=".ui.ChooseContactActivity"
200            android:label="@string/title_activity_choose_contact"
201            android:exported="true" />
202        <activity
203            android:name=".ui.BlocklistActivity"
204            android:label="@string/title_activity_block_list"
205            android:exported="true"/>
206        <activity
207            android:name=".ui.ChangePasswordActivity"
208            android:label="@string/change_password_on_server"
209            android:exported="true"/>
210        <activity
211            android:name=".ui.ChooseAccountForProfilePictureActivity"
212            android:enabled="false"
213            android:label="@string/choose_account"
214            android:exported="true">
215            <intent-filter android:label="@string/set_profile_picture">
216                <action android:name="android.intent.action.ATTACH_DATA" />
217
218                <category android:name="android.intent.category.DEFAULT" />
219
220                <data android:mimeType="image/*" />
221            </intent-filter>
222        </activity>
223        <activity
224            android:name=".ui.ShareViaAccountActivity"
225            android:label="@string/title_activity_share_via_account"
226            android:launchMode="singleTop"
227            android:exported="true" />
228        <activity
229            android:name=".ui.EditAccountActivity"
230            android:launchMode="singleTop"
231            android:exported="true"
232            android:windowSoftInputMode="stateHidden|adjustResize" />
233        <activity
234            android:name=".ui.ConferenceDetailsActivity"
235            android:label="@string/action_muc_details"
236            android:exported="true"
237            android:windowSoftInputMode="stateHidden" />
238        <activity
239            android:name=".ui.ContactDetailsActivity"
240            android:exported="true"
241            android:windowSoftInputMode="stateHidden" />
242        <activity
243            android:name=".ui.PublishProfilePictureActivity"
244            android:label="@string/mgmt_account_publish_avatar"
245            android:exported="true"
246            android:windowSoftInputMode="stateHidden" />
247        <activity
248            android:name=".ui.PublishGroupChatProfilePictureActivity"
249            android:exported="true"
250            android:label="@string/group_chat_avatar" />
251        <activity
252            android:name=".ui.ShareWithActivity"
253            android:label="@string/app_name"
254            android:launchMode="singleTop"
255            android:exported="true">
256            <intent-filter>
257                <action android:name="android.intent.action.SEND" />
258                <action android:name="android.intent.action.SEND_MULTIPLE" />
259
260                <category android:name="android.intent.category.DEFAULT" />
261
262                <data android:mimeType="text/plain" />
263            </intent-filter>
264            <intent-filter>
265                <action android:name="android.intent.action.SEND" />
266                <action android:name="android.intent.action.SEND_MULTIPLE" />
267
268                <category android:name="android.intent.category.DEFAULT" />
269
270                <data android:mimeType="*/*" />
271            </intent-filter>
272
273            <!-- the value here needs to be the full class name; independent of the configured applicationId -->
274            <meta-data
275                android:name="android.service.chooser.chooser_target_service"
276                android:value="eu.siacs.conversations.services.ContactChooserTargetService" />
277        </activity>
278        <activity
279            android:name=".ui.TrustKeysActivity"
280            android:label="@string/trust_omemo_fingerprints"
281            android:exported="true"
282            android:windowSoftInputMode="stateAlwaysHidden" />
283        <activity
284            android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
285            android:exported="true"
286            android:theme="@style/Base.Theme.AppCompat" />
287        <activity android:name=".ui.MemorizingActivity"
288            android:exported="true" />
289        <activity
290            android:name=".ui.MediaBrowserActivity"
291            android:exported="true"
292            android:label="@string/media_browser" />
293
294        <service android:name=".services.ExportBackupService" android:exported="true"/>
295        <service android:name=".services.ImportBackupService" android:exported="true"/>
296        <service
297            android:name=".services.ContactChooserTargetService"
298            android:permission="android.permission.BIND_CHOOSER_TARGET_SERVICE"
299            android:exported="true">
300            <intent-filter>
301                <action android:name="android.service.chooser.ChooserTargetService" />
302            </intent-filter>
303        </service>
304        <service android:name=".services.CompulsoryUpdateService" android:exported="true"/>
305
306        <provider
307            android:name="androidx.core.content.FileProvider"
308            android:authorities="${applicationId}.files"
309            android:exported="false"
310            android:grantUriPermissions="true">
311            <meta-data
312                android:name="android.support.FILE_PROVIDER_PATHS"
313                android:resource="@xml/file_paths" />
314        </provider>
315        <provider
316            android:name=".services.BarcodeProvider"
317            android:authorities="${applicationId}.barcodes"
318            android:exported="false"
319            android:grantUriPermissions="true" />
320
321        <activity
322            android:name=".ui.ShortcutActivity"
323            android:label="@string/contact"
324            android:exported="true">
325            <intent-filter>
326                <action android:name="android.intent.action.CREATE_SHORTCUT" />
327            </intent-filter>
328        </activity>
329        <activity
330            android:name=".ui.MucUsersActivity"
331            android:exported="true"
332            android:label="@string/group_chat_members" />
333        <activity
334            android:name=".ui.ChannelDiscoveryActivity"
335            android:exported="true"
336            android:label="@string/discover_channels" />
337        <activity
338            android:name=".ui.RtpSessionActivity"
339            android:autoRemoveFromRecents="true"
340            android:exported="true"
341            android:launchMode="singleInstance"
342            android:supportsPictureInPicture="true" />
343    </application>
344
345</manifest>
346<?xml version="1.0" encoding="utf-8"?>
347<manifest xmlns:android="http://schemas.android.com/apk/res/android"
348    xmlns:tools="http://schemas.android.com/tools"
349    package="eu.siacs.conversations">
350
351    <application tools:ignore="GoogleAppIndexingWarning">
352        <activity
353            android:name=".ui.ManageAccountActivity"
354            android:label="@string/title_activity_manage_accounts"
355            android:launchMode="singleTask"
356            android:exported="true"/>
357        <activity
358            android:name=".ui.MagicCreateActivity"
359            android:label="@string/create_new_account"
360            android:launchMode="singleTask"
361            android:exported="true"/>
362        <activity
363            android:name=".ui.EasyOnboardingInviteActivity"
364            android:label="@string/invite_to_app"
365            android:launchMode="singleTask" />
366        <activity
367            android:name=".ui.ImportBackupActivity"
368            android:label="@string/restore_backup"
369            android:launchMode="singleTask"
370            android:exported="true">
371            <intent-filter>
372                <action android:name="android.intent.action.VIEW" />
373                <category android:name="android.intent.category.DEFAULT" />
374
375                <data android:mimeType="application/vnd.conversations.backup" />
376                <data android:scheme="content" />
377            </intent-filter>
378            <intent-filter>
379                <action android:name="android.intent.action.VIEW" />
380                <category android:name="android.intent.category.DEFAULT" />
381
382                <data android:mimeType="application/vnd.conversations.backup" />
383                <data android:scheme="file" />
384            </intent-filter>
385            <intent-filter>
386                <action android:name="android.intent.action.VIEW" />
387
388                <category android:name="android.intent.category.DEFAULT" />
389                <category android:name="android.intent.category.BROWSABLE" />
390
391                <data android:scheme="content" />
392                <data android:host="*" />
393                <data android:mimeType="*/*" />
394                <data android:pathPattern=".*\\.ceb" />
395                <data android:pathPattern=".*\\..*\\.ceb" />
396                <data android:pathPattern=".*\\..*\\..*\\.ceb" />
397                <data android:pathPattern=".*\\..*\\..*\\..*\\.ceb" />
398                <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\.ceb" />
399                <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\.ceb" />
400                <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\..*\\.ceb" />
401            </intent-filter>
402            <intent-filter>
403                <action android:name="android.intent.action.VIEW" />
404
405                <category android:name="android.intent.category.DEFAULT" />
406                <category android:name="android.intent.category.BROWSABLE" />
407
408                <data android:scheme="file" />
409                <data android:host="*" />
410                <data android:mimeType="*/*" />
411                <data android:pathPattern=".*\\.ceb" />
412                <data android:pathPattern=".*\\..*\\.ceb" />
413                <data android:pathPattern=".*\\..*\\..*\\.ceb" />
414                <data android:pathPattern=".*\\..*\\..*\\..*\\.ceb" />
415                <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\.ceb" />
416                <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\.ceb" />
417                <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\..*\\.ceb" />
418            </intent-filter>
419        </activity>
420    </application>
421</manifest>
422
423

My gradle file:

1<?xml version="1.0" encoding="utf-8"?>
2<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3    xmlns:tools="http://schemas.android.com/tools"
4    package="eu.siacs.conversations">
5
6    <uses-sdk tools:overrideLibrary="net.ypresto.androidtranscoder" />
7
8    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
9    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
10    <uses-permission android:name="android.permission.READ_CONTACTS" />
11    <uses-permission android:name="android.permission.READ_PROFILE" />
12    <uses-permission
13        android:name="android.permission.READ_PHONE_STATE"
14        android:maxSdkVersion="22" />
15    <uses-permission android:name="android.permission.INTERNET" />
16    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
17    <uses-permission android:name="android.permission.WAKE_LOCK" />
18    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
19    <uses-permission android:name="android.permission.VIBRATE" />
20    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
21    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
22    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
23    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
24    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
25    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
26
27    <uses-feature
28        android:name="android.hardware.location"
29        android:required="false" />
30    <uses-feature
31        android:name="android.hardware.location.gps"
32        android:required="false" />
33    <uses-feature
34        android:name="android.hardware.location.network"
35        android:required="false" />
36
37    <uses-permission android:name="android.permission.CAMERA" />
38    <uses-permission android:name="android.permission.RECORD_AUDIO" />
39    <uses-permission android:name="android.permission.BLUETOOTH" />
40    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
41    <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
42    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
43
44    <uses-feature
45        android:name="android.hardware.camera"
46        android:required="false" />
47    <uses-feature
48        android:name="android.hardware.camera.autofocus"
49        android:required="false" />
50    <uses-feature
51        android:name="android.hardware.microphone"
52        android:required="false" />
53
54    <application
55        android:name=".Application"
56        android:allowBackup="false"
57        android:allowClearUserData="true"
58        android:appCategory="social"
59        android:hardwareAccelerated="true"
60        android:icon="@mipmap/ic_app_launch"
61        android:label="@string/app_name"
62        android:largeHeap="true"
63        android:networkSecurityConfig="@xml/network_security_configuration"
64        android:requestLegacyExternalStorage="true"
65        android:roundIcon="@mipmap/ic_app_launch_round"
66        android:theme="@style/ConversationsTheme"
67        android:usesCleartextTraffic="true"
68        android:windowSoftInputMode="adjustPan|adjustResize"
69        tools:replace="android:label"
70        tools:targetApi="q">
71        <activity
72            android:name=".ui.search.GroupSearchActivity"
73            android:exported="true" />
74        <activity
75            android:name=".ui.profileUpdating.FavouritesActivity"
76            android:exported="true" />
77        <activity
78            android:name=".ui.profileUpdating.NameActivity"
79            android:exported="true" />
80        <activity
81            android:name=".ui.CompulsoryUpdateActivity"
82            android:exported="true" />
83        <activity android:name=".ui.payments.doPayment.DoPaymentActivity"
84            android:exported="true" />
85        <activity android:name=".ui.individualList.IndividualListActivity"
86            android:exported="true" />
87        <activity android:name=".ui.payments.setPayment.SetPaymentActivity"
88            android:exported="true" />
89        <activity android:name=".ui.login.otpActivity.OTPActivity"
90            android:exported="true" />
91        <activity android:name=".ui.login.loginActivity.LoginActivity"
92            android:exported="true" />
93
94        <service android:name=".services.XmppConnectionService" android:exported="true" />
95
96        <receiver android:name=".services.EventReceiver"
97            android:exported="true">
98            <intent-filter>
99                <action android:name="android.intent.action.BOOT_COMPLETED" />
100                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
101                <action android:name="android.intent.action.ACTION_SHUTDOWN" />
102                <action android:name="android.media.RINGER_MODE_CHANGED" />
103            </intent-filter>
104        </receiver>
105
106        <activity
107            android:name=".ui.ShareLocationActivity"
108            android:label="@string/title_activity_share_location"
109            android:exported="true"/>
110        <activity
111            android:name=".ui.SearchActivity"
112            android:label="@string/search_messages"
113            android:exported="true" />
114        <activity
115            android:name=".ui.RecordingActivity"
116            android:configChanges="orientation|screenSize"
117            android:theme="@style/ConversationsTheme.Dialog"
118            android:exported="true" />
119        <activity
120            android:name=".ui.ShowLocationActivity"
121            android:label="@string/title_activity_show_location"
122            android:exported="true" />
123        <activity
124            android:name=".ui.SplashActivity"
125            android:theme="@style/SplashTheme"
126            android:exported="true">
127            <intent-filter>
128                <action android:name="android.intent.action.MAIN" />
129
130                <category android:name="android.intent.category.LAUNCHER" />
131            </intent-filter>
132        </activity>
133        <activity
134            android:name=".ui.ConversationsActivity"
135            android:label="@string/app_name"
136            android:launchMode="singleTask"
137            android:minWidth="300dp"
138            android:minHeight="300dp"
139            android:exported="true"
140            android:windowSoftInputMode="stateHidden" />
141        <activity
142            android:name=".ui.ScanActivity"
143            android:screenOrientation="portrait"
144            android:exported="true"
145            android:theme="@style/ConversationsTheme.FullScreen"
146            android:windowSoftInputMode="stateAlwaysHidden" />
147        <activity
148            android:name=".ui.UriHandlerActivity"
149            android:label="@string/app_name"
150            android:exported="true">
151            <intent-filter>
152                <action android:name="android.intent.action.VIEW" />
153
154                <category android:name="android.intent.category.DEFAULT" />
155                <category android:name="android.intent.category.BROWSABLE" />
156
157                <data android:scheme="xmpp" />
158            </intent-filter>
159            <intent-filter android:autoVerify="true">
160                <action android:name="android.intent.action.VIEW" />
161
162                <category android:name="android.intent.category.DEFAULT" />
163                <category android:name="android.intent.category.BROWSABLE" />
164
165                <data android:scheme="https" />
166                <data android:host="im.app.in" />
167                <data android:pathPrefix="/i/" />
168                <data android:pathPrefix="/j/" />
169            </intent-filter>
170            <intent-filter>
171                <action android:name="android.intent.action.SENDTO" />
172
173                <category android:name="android.intent.category.DEFAULT" />
174
175                <data android:scheme="imto" />
176                <data android:host="jabber" />
177            </intent-filter>
178        </activity>
179        <activity
180            android:name=".ui.StartConversationActivity"
181            android:label="@string/title_activity_start_conversation"
182            android:launchMode="singleTop"
183            android:exported="true">
184            <intent-filter>
185                <action android:name="android.intent.action.VIEW" />
186            </intent-filter>
187        </activity>
188        <activity
189            android:name=".ui.SettingsActivity"
190            android:label="@string/title_activity_settings"
191            android:exported="true">
192            <intent-filter>
193                <action android:name="android.intent.action.MAIN" />
194
195                <category android:name="android.intent.category.NOTIFICATION_PREFERENCES" />
196            </intent-filter>
197        </activity>
198        <activity
199            android:name=".ui.ChooseContactActivity"
200            android:label="@string/title_activity_choose_contact"
201            android:exported="true" />
202        <activity
203            android:name=".ui.BlocklistActivity"
204            android:label="@string/title_activity_block_list"
205            android:exported="true"/>
206        <activity
207            android:name=".ui.ChangePasswordActivity"
208            android:label="@string/change_password_on_server"
209            android:exported="true"/>
210        <activity
211            android:name=".ui.ChooseAccountForProfilePictureActivity"
212            android:enabled="false"
213            android:label="@string/choose_account"
214            android:exported="true">
215            <intent-filter android:label="@string/set_profile_picture">
216                <action android:name="android.intent.action.ATTACH_DATA" />
217
218                <category android:name="android.intent.category.DEFAULT" />
219
220                <data android:mimeType="image/*" />
221            </intent-filter>
222        </activity>
223        <activity
224            android:name=".ui.ShareViaAccountActivity"
225            android:label="@string/title_activity_share_via_account"
226            android:launchMode="singleTop"
227            android:exported="true" />
228        <activity
229            android:name=".ui.EditAccountActivity"
230            android:launchMode="singleTop"
231            android:exported="true"
232            android:windowSoftInputMode="stateHidden|adjustResize" />
233        <activity
234            android:name=".ui.ConferenceDetailsActivity"
235            android:label="@string/action_muc_details"
236            android:exported="true"
237            android:windowSoftInputMode="stateHidden" />
238        <activity
239            android:name=".ui.ContactDetailsActivity"
240            android:exported="true"
241            android:windowSoftInputMode="stateHidden" />
242        <activity
243            android:name=".ui.PublishProfilePictureActivity"
244            android:label="@string/mgmt_account_publish_avatar"
245            android:exported="true"
246            android:windowSoftInputMode="stateHidden" />
247        <activity
248            android:name=".ui.PublishGroupChatProfilePictureActivity"
249            android:exported="true"
250            android:label="@string/group_chat_avatar" />
251        <activity
252            android:name=".ui.ShareWithActivity"
253            android:label="@string/app_name"
254            android:launchMode="singleTop"
255            android:exported="true">
256            <intent-filter>
257                <action android:name="android.intent.action.SEND" />
258                <action android:name="android.intent.action.SEND_MULTIPLE" />
259
260                <category android:name="android.intent.category.DEFAULT" />
261
262                <data android:mimeType="text/plain" />
263            </intent-filter>
264            <intent-filter>
265                <action android:name="android.intent.action.SEND" />
266                <action android:name="android.intent.action.SEND_MULTIPLE" />
267
268                <category android:name="android.intent.category.DEFAULT" />
269
270                <data android:mimeType="*/*" />
271            </intent-filter>
272
273            <!-- the value here needs to be the full class name; independent of the configured applicationId -->
274            <meta-data
275                android:name="android.service.chooser.chooser_target_service"
276                android:value="eu.siacs.conversations.services.ContactChooserTargetService" />
277        </activity>
278        <activity
279            android:name=".ui.TrustKeysActivity"
280            android:label="@string/trust_omemo_fingerprints"
281            android:exported="true"
282            android:windowSoftInputMode="stateAlwaysHidden" />
283        <activity
284            android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
285            android:exported="true"
286            android:theme="@style/Base.Theme.AppCompat" />
287        <activity android:name=".ui.MemorizingActivity"
288            android:exported="true" />
289        <activity
290            android:name=".ui.MediaBrowserActivity"
291            android:exported="true"
292            android:label="@string/media_browser" />
293
294        <service android:name=".services.ExportBackupService" android:exported="true"/>
295        <service android:name=".services.ImportBackupService" android:exported="true"/>
296        <service
297            android:name=".services.ContactChooserTargetService"
298            android:permission="android.permission.BIND_CHOOSER_TARGET_SERVICE"
299            android:exported="true">
300            <intent-filter>
301                <action android:name="android.service.chooser.ChooserTargetService" />
302            </intent-filter>
303        </service>
304        <service android:name=".services.CompulsoryUpdateService" android:exported="true"/>
305
306        <provider
307            android:name="androidx.core.content.FileProvider"
308            android:authorities="${applicationId}.files"
309            android:exported="false"
310            android:grantUriPermissions="true">
311            <meta-data
312                android:name="android.support.FILE_PROVIDER_PATHS"
313                android:resource="@xml/file_paths" />
314        </provider>
315        <provider
316            android:name=".services.BarcodeProvider"
317            android:authorities="${applicationId}.barcodes"
318            android:exported="false"
319            android:grantUriPermissions="true" />
320
321        <activity
322            android:name=".ui.ShortcutActivity"
323            android:label="@string/contact"
324            android:exported="true">
325            <intent-filter>
326                <action android:name="android.intent.action.CREATE_SHORTCUT" />
327            </intent-filter>
328        </activity>
329        <activity
330            android:name=".ui.MucUsersActivity"
331            android:exported="true"
332            android:label="@string/group_chat_members" />
333        <activity
334            android:name=".ui.ChannelDiscoveryActivity"
335            android:exported="true"
336            android:label="@string/discover_channels" />
337        <activity
338            android:name=".ui.RtpSessionActivity"
339            android:autoRemoveFromRecents="true"
340            android:exported="true"
341            android:launchMode="singleInstance"
342            android:supportsPictureInPicture="true" />
343    </application>
344
345</manifest>
346<?xml version="1.0" encoding="utf-8"?>
347<manifest xmlns:android="http://schemas.android.com/apk/res/android"
348    xmlns:tools="http://schemas.android.com/tools"
349    package="eu.siacs.conversations">
350
351    <application tools:ignore="GoogleAppIndexingWarning">
352        <activity
353            android:name=".ui.ManageAccountActivity"
354            android:label="@string/title_activity_manage_accounts"
355            android:launchMode="singleTask"
356            android:exported="true"/>
357        <activity
358            android:name=".ui.MagicCreateActivity"
359            android:label="@string/create_new_account"
360            android:launchMode="singleTask"
361            android:exported="true"/>
362        <activity
363            android:name=".ui.EasyOnboardingInviteActivity"
364            android:label="@string/invite_to_app"
365            android:launchMode="singleTask" />
366        <activity
367            android:name=".ui.ImportBackupActivity"
368            android:label="@string/restore_backup"
369            android:launchMode="singleTask"
370            android:exported="true">
371            <intent-filter>
372                <action android:name="android.intent.action.VIEW" />
373                <category android:name="android.intent.category.DEFAULT" />
374
375                <data android:mimeType="application/vnd.conversations.backup" />
376                <data android:scheme="content" />
377            </intent-filter>
378            <intent-filter>
379                <action android:name="android.intent.action.VIEW" />
380                <category android:name="android.intent.category.DEFAULT" />
381
382                <data android:mimeType="application/vnd.conversations.backup" />
383                <data android:scheme="file" />
384            </intent-filter>
385            <intent-filter>
386                <action android:name="android.intent.action.VIEW" />
387
388                <category android:name="android.intent.category.DEFAULT" />
389                <category android:name="android.intent.category.BROWSABLE" />
390
391                <data android:scheme="content" />
392                <data android:host="*" />
393                <data android:mimeType="*/*" />
394                <data android:pathPattern=".*\\.ceb" />
395                <data android:pathPattern=".*\\..*\\.ceb" />
396                <data android:pathPattern=".*\\..*\\..*\\.ceb" />
397                <data android:pathPattern=".*\\..*\\..*\\..*\\.ceb" />
398                <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\.ceb" />
399                <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\.ceb" />
400                <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\..*\\.ceb" />
401            </intent-filter>
402            <intent-filter>
403                <action android:name="android.intent.action.VIEW" />
404
405                <category android:name="android.intent.category.DEFAULT" />
406                <category android:name="android.intent.category.BROWSABLE" />
407
408                <data android:scheme="file" />
409                <data android:host="*" />
410                <data android:mimeType="*/*" />
411                <data android:pathPattern=".*\\.ceb" />
412                <data android:pathPattern=".*\\..*\\.ceb" />
413                <data android:pathPattern=".*\\..*\\..*\\.ceb" />
414                <data android:pathPattern=".*\\..*\\..*\\..*\\.ceb" />
415                <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\.ceb" />
416                <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\.ceb" />
417                <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\..*\\.ceb" />
418            </intent-filter>
419        </activity>
420    </application>
421</manifest>
422
423import com.android.build.OutputFile
424
425// Top-level build file where you can add configuration options common to all
426// sub-projects/modules.
427buildscript {
428    ext.kotlin_version = "1.5.21"
429    repositories {
430        google()
431        mavenCentral()
432        maven { url 'https://jitpack.io' }
433        gradlePluginPortal()
434    }
435    dependencies {
436        classpath 'com.android.tools.build:gradle:4.2.2'
437        classpath 'com.google.gms:google-services:4.3.8'
438        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
439    }
440}
441
442apply plugin: 'com.android.application'
443apply plugin: 'kotlin-android'
444apply plugin: 'kotlin-kapt'
445apply plugin: 'com.google.gms.google-services'
446
447repositories {
448    google()
449    mavenCentral()
450    jcenter()
451    maven { url 'https://jitpack.io' }
452}
453
454configurations {
455    conversationsFreeCompatImplementation
456}
457
458dependencies {
459    implementation 'androidx.viewpager:viewpager:1.0.0'
460    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
461
462    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
463
464    implementation 'org.sufficientlysecure:openpgp-api:10.0'
465    implementation 'com.theartofdev.edmodo:android-image-cropper:2.8.0'
466    implementation 'androidx.appcompat:appcompat:1.3.1'
467    implementation 'androidx.exifinterface:exifinterface:1.3.2'
468    implementation 'androidx.cardview:cardview:1.0.0'
469    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
470    implementation 'androidx.emoji:emoji:1.1.0'
471    implementation 'com.google.android.material:material:1.4.0'
472    conversationsFreeCompatImplementation 'androidx.emoji:emoji-bundled:1.1.0'
473    implementation 'org.bouncycastle:bcmail-jdk15on:1.64'
474    //zxing stopped supporting Java 7 so we have to stick with 3.3.3
475    //https://github.com/zxing/zxing/issues/1170
476    implementation 'com.google.zxing:core:3.4.1'
477    implementation 'de.measite.minidns:minidns-hla:0.2.4'
478    implementation 'me.leolin:ShortcutBadger:1.1.22@aar'
479    implementation 'org.whispersystems:signal-protocol-java:2.8.1'
480    implementation 'com.makeramen:roundedimageview:2.3.0'
481    implementation "com.wefika:flowlayout:0.4.1"
482    implementation 'net.ypresto.androidtranscoder:android-transcoder:0.3.0'
483    implementation 'org.jxmpp:jxmpp-jid:1.0.1'
484    implementation 'org.osmdroid:osmdroid-android:6.1.10'
485    implementation 'org.hsluv:hsluv:0.2'
486    implementation 'org.conscrypt:conscrypt-android:2.5.2'
487    implementation 'me.drakeet.support:toastcompat:1.1.0'
488    implementation "com.leinardi.android:speed-dial:3.2.0"
489
490    implementation "com.squareup.retrofit2:retrofit:2.9.0"
491    implementation "com.squareup.retrofit2:converter-gson:2.9.0"
492    implementation "com.squareup.okhttp3:okhttp:5.0.0-alpha.2"
493    implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2'
494
495    implementation 'com.google.guava:guava:30.1.1-android'
496    implementation 'org.webrtc:google-webrtc:1.0.32006'
497
498    // Lifecycle Helper
499    implementation "androidx.activity:activity-ktx:1.3.0-rc02"
500    implementation "androidx.fragment:fragment-ktx:1.3.6"
501
502    //Navigation
503    implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
504    implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'
505
506    //CardView
507    implementation "androidx.cardview:cardview:1.0.0"
508
509    //Country Code Picker
510    implementation 'com.hbb20:ccp:2.5.3'
511
512    //Firebase
513    implementation 'com.google.firebase:firebase-bom:28.3.0'
514    implementation 'com.google.firebase:firebase-auth-ktx:21.0.1'
515    implementation 'androidx.browser:browser:1.3.0'
516
517    //OTP view
518    implementation 'com.github.mukeshsolanki:android-otpview-pinview:2.1.2'
519
520    //Retrofit
521    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
522    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
523
524    //Gson
525    implementation 'com.google.code.gson:gson:2.8.7'
526
527    //Multidex
528    implementation 'androidx.multidex:multidex:2.0.1'
529
530    //Round Image
531    implementation 'de.hdodenhof:circleimageview:3.1.0'
532
533    // Button with image and text
534    implementation 'com.github.Omega-R:OmegaCenterIconButton:0.0.4@aar'
535
536    //Razor pay
537    implementation 'com.razorpay:checkout:1.6.10'
538
539    //Mixpanel Tracking
540    implementation 'com.mixpanel.android:mixpanel-android:5.9.1'
541
542    //Loading screen
543    implementation 'com.wang.avi:library:2.1.3'
544
545    //Loading
546    implementation 'com.wang.avi:library:2.1.3'
547
548    //Form
549    implementation 'com.quickbirdstudios:surveykit:1.1.0'
550}
551
552ext {
553    travisBuild = System.getenv("TRAVIS") == "true"
554    preDexEnabled = System.getProperty("pre-dex", "true")
555    abiCodes = ['armeabi-v7a': 1, 'x86': 2, 'x86_64': 3, 'arm64-v8a': 4]
556}
557
558android {
559    compileSdkVersion 31
560
561    defaultConfig {
562        minSdkVersion 24
563        targetSdkVersion 31
564        versionCode 44
565        versionName "2.0.4"
566        multiDexEnabled = true
567        archivesBaseName += "-$versionName"
568        applicationId "com.app.app"
569        resValue "string", "applicationId", applicationId
570        def appName = "app"
571        resValue "string", "app_name", appName
572        buildConfigField "String", "APP_NAME", "\"$appName\""
573    }
574
575    splits {
576        abi {
577            universalApk true
578            enable true
579        }
580    }
581
582    configurations {
583        compile.exclude group: 'org.jetbrains' , module:'annotations'
584    }
585
586    dataBinding {
587        enabled true
588    }
589
590    dexOptions {
591        // Skip pre-dexing when running on Travis CI or when disabled via -Dpre-dex=false.
592        preDexLibraries = preDexEnabled && !travisBuild
593        jumboMode true
594    }
595
596    compileOptions {
597        sourceCompatibility JavaVersion.VERSION_1_8
598        targetCompatibility JavaVersion.VERSION_1_8
599    }
600
601    flavorDimensions("mode", "distribution", "emoji")
602
603    productFlavors {
604
605        conversations {
606            dimension "mode"
607        }
608        free {
609            dimension "distribution"
610            versionNameSuffix "+f"
611        }
612        compat {
613            dimension "emoji"
614            versionNameSuffix "c"
615        }
616    }
617
618    sourceSets {
619        conversationsFreeCompat {
620            java {
621                srcDir 'src/freeCompat/java'
622                srcDir 'src/conversationsFree/java'
623            }
624        }
625    }
626
627    buildTypes {
628        release {
629            shrinkResources true
630            minifyEnabled true
631            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
632            versionNameSuffix "r"
633        }
634        debug {
635            shrinkResources true
636            minifyEnabled true
637            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
638            versionNameSuffix "d"
639        }
640    }
641
642
643    if (new File("signing.properties").exists()) {
644        Properties props = new Properties()
645        props.load(new FileInputStream(file("signing.properties")))
646
647        signingConfigs {
648            release {
649                storeFile file(props['keystore'])
650                storePassword props['keystore.password']
651                keyAlias props['keystore.alias']
652                keyPassword props['keystore.password']
653            }
654        }
655        buildTypes.release.signingConfig = signingConfigs.release
656    }
657
658    lintOptions {
659        disable 'MissingTranslation', 'InvalidPackage','AppCompatResource'
660    }
661
662    subprojects {
663
664        afterEvaluate {
665            if (getPlugins().hasPlugin('android') ||
666                    getPlugins().hasPlugin('android-library')) {
667
668                configure(android.lintOptions) {
669                    disable 'AndroidGradlePluginVersion', 'MissingTranslation'
670                }
671            }
672
673        }
674    }
675
676    packagingOptions {
677        exclude 'META-INF/BCKEY.DSA'
678        exclude 'META-INF/BCKEY.SF'
679    }
680
681    android.applicationVariants.all { variant ->
682        variant.outputs.each { output ->
683            def baseAbiVersionCode = project.ext.abiCodes.get(output.getFilter(OutputFile.ABI))
684            if (baseAbiVersionCode != null) {
685                output.versionCodeOverride = (100 * variant.versionCode) + baseAbiVersionCode
686            }
687        }
688
689    }
690}
691

ANSWER

Answered 2021-Aug-04 at 09:18

I'm not sure what you're using to code, but in order to set it in Android Studio, open the manifest of your project and under the "activity" section, put android:exported="true"(or false if that is what you prefer). I have attached an example.

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

QUESTION

uploaded an APK which has an activity,activity alias,service or broadcast receiver with intentfilter, but without 'android : exported' property set

Asked 2022-Feb-03 at 10:56

I'm having an issue when i'm uploading app bundle to the play console that You uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter, but without 'android:exported' property set. This file can't be installed on Android 12 or higher. but my manifest file includes the property.

Manifest file

1    <?xml version="1.0" encoding="utf-8"?>
2    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3        package="**********">
4        <!-- io.flutter.app.FlutterApplication is an android.app.Application that
5             calls FlutterMain.startInitialization(this); in its onCreate method.
6             In most cases you can leave this as-is, but you if you want to provide
7             additional functionality it is fine to subclass or reimplement
8             FlutterApplication and put your custom class here. -->
9        <uses-permission android:name="android.permission.INTERNET" />
10        <uses-permission android:name="android.permission.CAMERA" />
11        <uses-feature android:name="android.hardware.camera" />
12        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
13        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
14        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
15        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
16        <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
17        <uses-permission android:name="android.permission.WAKE_LOCK"/>
18        <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
19        <uses-permission android:name="android.permission.VIBRATE" />
20        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
21        <uses-permission android:name="android.permission.WAKE_LOCK" />
22        <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
23        <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
24    
25    
26        <application
27            android:name="io.flutter.app.FlutterApplication"
28            android:label="*****"
29            android:requestLegacyExternalStorage="true"
30            android:usesCleartextTraffic="true"
31            android:icon="@mipmap/ic_launcher">
32    
33    
34            <meta-data
35              android:name="com.google.firebase.messaging.default_notification_icon"
36              android:resource="@drawable/ic_stat_artboard_1" />
37    
38            <meta-data android:name="com.google.android.geo.API_KEY"
39                android:value="Z*********"/>
40    
41            <provider
42                android:name="vn.hunghd.flutterdownloader.DownloadedFileProvider"
43                android:authorities="im.mingguang.mingguang_app.flutter_downloader.provider"
44                android:grantUriPermissions="true"
45                android:requestLegacyExternalStorage="true">
46                <meta-data
47                    android:name="android.support.FILE_PROVIDER_PATHS"
48                    android:resource="@xml/provider_paths"/>
49            </provider>
50    
51            <provider
52        android:name="androidx.core.content.FileProvider"
53        android:authorities="${applicationId}.provider"
54        android:grantUriPermissions="true">
55        <meta-data
56            android:name="android.support.FILE_PROVIDER_PATHS"
57            android:resource="@xml/provider_paths"/>
58    </provider>
59            <activity
60                android:name=".MainActivity"
61                android:launchMode="singleTop"
62                android:theme="@style/LaunchTheme"
63                android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
64                android:hardwareAccelerated="true"
65                android:exported="true"
66                android:windowSoftInputMode="adjustResize">
67                <intent-filter>
68                    <action android:name="android.intent.action.MAIN"/>
69                    <category android:name="android.intent.category.DEFAULT"/>
70                    <category android:name="android.intent.category.LAUNCHER"/>
71                </intent-filter>
72                <intent-filter>
73                    <action android:name="FLUTTER_NOTIFICATION_CLICK" />
74                    <category android:name="android.intent.category.DEFAULT"/>
75                </intent-filter>
76            </activity>
77            <!-- Don't delete the meta-data below.
78                 This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
79            <meta-data
80                android:name="flutterEmbedding"
81                android:value="2" />
82        </application>
83    </manifest>
84

Play Console Error

enter image description here

ANSWER

Answered 2022-Jan-12 at 23:56

I face the same Issue but i solved by writing android:exported="true" in activity bellow the android:name=".MainActivity" image shown

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

QUESTION

What's the mathematical reason behind Python choosing to round integer division toward negative infinity?

Asked 2022-Jan-30 at 01:29

I know Python // rounds towards negative infinity and in C++ / is truncating, rounding towards 0.

And here's what I know so far:

1               |remainder|
2-12 / 10  = -1,   - 2      // C++
3-12 // 10 = -2,   + 8      # Python
4
512 / -10  = -1,     2      // C++
612 // -10 = -2,   - 8      # Python
7
812 / 10  = 1,      2       // Both
912 // 10 = 1,      2
10
11-12 / -10 = 1,    - 2      // Both
12          = 2,    + 8
13
14C++:
151. m%(-n) == m%n
162. -m%n == -(m%n)
173. (m/n)*n + m%n == m
18
19Python:
201. m%(-n) == -8 == -(-m%n)
212. (m//n)*n + m%n == m
22

But why Python // choose to round towards negative infinity? I didn't find any resources explain that, but only find and hear people say vaguely: "for mathematics reasons".

For example, in Why is -1/2 evaluated to 0 in C++, but -1 in Python?:

People dealing with these things in the abstract tend to feel that rounding toward negative infinity makes more sense (that means it's compatible with the modulo function as defined in mathematics, rather than % having a somewhat funny meaning).

But I don't see C++ 's / not being compatible with the modulo function. In C++, (m/n)*n + m%n == m also applies.

So what's the (mathematical) reason behind Python choosing rounding towards negative infinity?


See also Guido van Rossum's old blog post on the topic.

ANSWER

Answered 2022-Jan-18 at 21:46

Although I can't provide a formal definition of why/how the rounding modes were chosen as they were, the citation about compatibility with the % operator, which you have included, does make sense when you consider that % is not quite the same thing in C++ and Python.

In C++, it is the remainder operator, whereas, in Python, it is the modulus operator – and, when the two operands have different signs, these aren't necessarily the same thing. There are some fine explanations of the difference between these operators in the answers to: What's the difference between “mod” and “remainder”?

Now, considering this difference, the rounding (truncation) modes for integer division have to be as they are in the two languages, to ensure that the relationship you quoted, (m/n)*n + m%n == m, remains valid.

Here are two short programs that demonstrate this in action (please forgive my somewhat naïve Python code – I'm a beginner in that language):

C++:

1               |remainder|
2-12 / 10  = -1,   - 2      // C++
3-12 // 10 = -2,   + 8      # Python
4
512 / -10  = -1,     2      // C++
612 // -10 = -2,   - 8      # Python
7
812 / 10  = 1,      2       // Both
912 // 10 = 1,      2
10
11-12 / -10 = 1,    - 2      // Both
12          = 2,    + 8
13
14C++:
151. m%(-n) == m%n
162. -m%n == -(m%n)
173. (m/n)*n + m%n == m
18
19Python:
201. m%(-n) == -8 == -(-m%n)
212. (m//n)*n + m%n == m
22#include <iostream>
23
24int main()
25{
26    int dividend, divisor, quotient, remainder, check;
27    std::cout << "Enter Dividend: ";                        // -27
28    std::cin >> dividend;
29    std::cout << "Enter Divisor: ";                         // 4
30    std::cin >> divisor;
31
32    quotient = dividend / divisor;
33    std::cout << "Quotient = " << quotient << std::endl;    // -6
34    remainder = dividend % divisor;
35    std::cout << "Remainder = " << remainder << std::endl;  // -3
36
37    check = quotient * divisor + remainder;
38    std::cout << "Check = " << check << std::endl;          // -27
39    return 0;
40}
41

Python:

1               |remainder|
2-12 / 10  = -1,   - 2      // C++
3-12 // 10 = -2,   + 8      # Python
4
512 / -10  = -1,     2      // C++
612 // -10 = -2,   - 8      # Python
7
812 / 10  = 1,      2       // Both
912 // 10 = 1,      2
10
11-12 / -10 = 1,    - 2      // Both
12          = 2,    + 8
13
14C++:
151. m%(-n) == m%n
162. -m%n == -(m%n)
173. (m/n)*n + m%n == m
18
19Python:
201. m%(-n) == -8 == -(-m%n)
212. (m//n)*n + m%n == m
22#include <iostream>
23
24int main()
25{
26    int dividend, divisor, quotient, remainder, check;
27    std::cout << "Enter Dividend: ";                        // -27
28    std::cin >> dividend;
29    std::cout << "Enter Divisor: ";                         // 4
30    std::cin >> divisor;
31
32    quotient = dividend / divisor;
33    std::cout << "Quotient = " << quotient << std::endl;    // -6
34    remainder = dividend % divisor;
35    std::cout << "Remainder = " << remainder << std::endl;  // -3
36
37    check = quotient * divisor + remainder;
38    std::cout << "Check = " << check << std::endl;          // -27
39    return 0;
40}
41print("Enter Dividend: ")             # -27
42dividend = int(input())
43print("Enter Divisor: ")              # 4
44divisor = int(input())
45quotient = dividend // divisor;
46print("Quotient = " + str(quotient))  # -7
47modulus = dividend % divisor;
48print("Modulus = " + str(modulus))    # 1
49check = quotient * divisor + modulus; # -27
50print("Check = " + str(check))
51

Note that, for the given inputs of different signs (-27 and 4), both the quotient and remainder/modulus are different between the languages but also that the restored check value is correct in both cases.

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

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in HTTP

Tutorials and Learning Resources are not available at this moment for HTTP

Share this Page

share link

Get latest updates on HTTP