Java

How to make Apache HttpClient trust Let's Encrypt Certificate Authority

<build> <resources> <resource> <directory>src/main/resources</directory> <filtering>false</filtering> </resource> </resources> </build> import javax.net.ssl.X509TrustManager; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class TrustManagerDelegate implements X509TrustManager { private final X509TrustManager mainTrustManager; private final X509TrustManager fallbackTrustManager; public TrustManagerDelegate(X509TrustManager mainTrustManager, X509TrustManager fallbackTrustManager) { this.mainTrustManager = mainTrustManager; this.fallbackTrustManager = fallbackTrustManager; } @Override public void checkClientTrusted(final X509Certificate[] x509Certificates, final String authType) throws CertificateException { try { mainTrustManager.checkClientTrusted(x509Certificates, authType); } catch(CertificateException ignored) { this.fallbackTrustManager.checkClientTrusted(x509Certificates, authType); } } @Override public void checkServerTrusted(final X509Certificate[] x509Certificates, final String authType) throws CertificateException { try { mainTrustManager.

Nepíšete javadoc komentáře? Díky Java 8 vězte, že dobře děláte!

user@hostname:~/www/project/myproject$ mvn javadoc:jar [ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.9.1:jar (default-cli) on project myproject: MavenReportException: Error while creating archive: [ERROR] /home/user/www/project/myproject/library/src/main/java/cz/sys/tis/AccidentList.java:181: error: bad use of '&gt;' [ERROR] * &lt;/element&gt; [ERROR] ^ [ERROR] /home/user/www/project/myproject/library/src/main/java/cz/sys/tis/ObjectFactory.java:75: warning: no @return [ERROR] public AccidentList.Accident.ImpactDescriptionList createAccidentListAccidentImpactDescriptionList() { [ERROR] ^ [ERROR] /home/user/www/project/myproject/library/src/main/java/cz/sys/tis/ObjectFactory.java:83: warning: no @return [ERROR] public AccidentList.Accident.AlternateSupplyList.AlternateSupplyItem createAccidentListAccidentAlternateSupplyListAlternateSupplyItem() { [ERROR] /home/user/www/project/myproject/library/src/main/java/com/fg/client/filter/CityOwnerRightsToDocumentFilter.java:125: warning - Tag @see:illegal character: &quot;64&quot; in &quot;{@link CityOwnerRightsToDocumentFilter#getCityCode(String)}&quot; [ERROR] /home/user/www/project/myproject/library/src/main/java/com/fg/client/model/price_list/PriceList.java:118: warning: no description for @return [ERROR] * @return [ERROR] ^ [ERROR] /home/user/www/project/myproject/library/src/main/java/com/fg/client/web/frontend/model/MapMarkerSet.

Serializujte optimálně skrze Kryo

Kryo kryo = new Kryo(); kryo.addDefaultSerializer(Trida.class, new TridaSerializer())); final ByteArrayOutputStream bos = new ByteArrayOutputStream(32768); try (Output output = new Output(bos)) { kryo.writeObject(output, clusteredResult); } return bos.toByteArray(); Kryo kryo = new Kryo(); kryo.addDefaultSerializer(Trida.class, new TridaSerializer())); try (Input input = new Input(stream)) { return kryo.readObject(input, resultType); }

Zbystřete své smysly technickými doplňky

<br /> {<br /> &quot;name&quot;:&quot;Ramjet Inspector&quot;,<br /> &quot;version&quot;:&quot;1.8&quot;,<br /> ... další povinné informace ...<br /> &quot;background&quot;:{<br /> &quot;scripts&quot;: [&quot;background.js&quot;]<br /> },<br /> &quot;permissions&quot;:[<br /> &quot;cookies&quot;,<br /> &quot;tabs&quot;,<br /> &quot;notifications&quot;,<br /> &quot;http://*/*&quot;,<br /> &quot;https://*/*&quot;,<br /> ],<br /> &quot;web_accessible_resources&quot;:[<br /> &quot;skin/INFO.png&quot;,<br /> &quot;skin/WARNING.png&quot;,<br /> &quot;skin/ERROR.png&quot;<br /> ]<br /> } var openNotifications = 0; //REGISTRACE LISTENERU NA ZMĚNY V COOKIES chrome.cookies.onChanged.addListener(function (data) { //zajímá nás pouze vytvoření cookie if (data.cause == "explicit" && data.

Spring profiles a použití v testech

@ContextConfiguration( locations = { "classpath:/META-INF/lib_mail/spring/test-context.xml" } ) public abstract class AbstractMessageStorageTestCase { @Autowired private MessageStorage messageStorage; @Test public void shouldPersistSimpleMessageBatch() { .... } @Test(expected = RecipientNotDefinedException.class) public void shouldFailToPersistMessageBatchWithoutRecipients() { .... } } @ContextConfiguration( locations = { "classpath:/META-INF/lib_mail/spring/mysql-datasource.xml", "classpath:META-INF/lib_mail/spring/mail-database-dao-config.xml" } ) public class MysqlMessageStorageTest extends AbstractMessageStorageTestCase { } @ContextConfiguration( locations = { "classpath:/META-INF/lib_mail/spring/memory-dao-config.xml" } )public class MemoryMessageStorageTest extends AbstractMessageStorageTestCase { } <?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <!-- sdílené konfigurace pro všechny testy --> <import resource="classpath:/META-INF/lib_mail/spring/mail-config.

K čemu je nám užitečný komponentový web framework?

<recordListing> <dataSource class="com.fg.SomeProvider"/> </recordListing> <recordListing> <dataSource class="com.fg.SomeProvider"/> <column id="firstName"/> <orderableColumn id="lastName"/> <column id="age"/> <pagination/> </recordListing> <recordListing> <dataSource class="com.fg.SomeProvider"/> <column id="firstName"/> <orderableColumn id="lastName"> <columnFilter> <textInput id="filter.byName"/> </columnFilter> </orderableColumn> <column id="age"> <columnFilter> <textInput id="filter.fromAge"> <validators><number/></validators> </textInput> <textInput id="filter.toAge"> <validators><number/></validators> </textInput> </columnFilter> </column> <pagination/> </recordListing>

Máte jistotu, že do session ukládáte pouze serializovatelné objekty?

public class SerializabilityCheckFilter implements Filter { private static final Log log = LogFactory.getLog(SerializabilityCheckFilter.class); public void init(FilterConfig filterConfig) throws ServletException { //nothing necessary to do } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { chain.doFilter(request, response); } finally { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpSession session = httpRequest.getSession(false); if (session != null) { boolean serializable = true; StringBuilder items = new StringBuilder(); Enumeration<String> names = session.

Commons File Upload contains a severe memory leak

public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) { DiskFileItem result = new DiskFileItem(fieldName, contentType, isFormField, fileName, sizeThreshold, repository); FileCleaningTracker tracker = getFileCleaningTracker(); if (tracker != null) { tracker.track(result.getTempFile(), this); } return result; } private static final class Tracker extends PhantomReference { private final String path; private final FileDeleteStrategy deleteStrategy; Tracker(String path, FileDeleteStrategy deleteStrategy, Object marker, ReferenceQueue queue) { super(marker, queue); this.path = path; this.deleteStrategy = (deleteStrategy == null ?

Springockito - výroba mocků snadno a rychle

<dependencies> ... <dependency> <groupId>org.kubek2k</groupId> <artifactId>springockito</artifactId> <version>1.0.4</version> <scope>test</scope> </dependency> <dependency> <groupId>org.kubek2k</groupId> <artifactId>springockito-annotations</artifactId> <version>1.0.2</version> <scope>test</scope> </dependency> ... </dependencies> @ContextConfiguration( loader = SpringockitoContextLoader.class, locations = "classpath:/context.xml" ) @RunWith(SpringJUnit4ClassRunner.class) public class SpringockitoAnnotationsMocksIntegrationTest { @ReplaceWithMock private InnerBean innerBean; ... } @After public void clearMocks() { Mockito.reset(innerBean) }

How do YOU test access control of your application?

@AllowedForAdministrator @AllowedForTerminalOrganizationOwner @DeniedForMerchant public void blockTerminal(Terminal terminal) { //business logic } @Test @RunAsUser("owner@fg.cz") public void shouldBlockTerminalAsOrganizationOwner() throws Exception { Terminal terminal = terminalManager.getTerminalById(100); assertNull(terminal.getDateBlocked()); terminalManager.blockTerminal(terminal); terminal = terminalManager.getTerminalById(100); assertNotNull(terminal.getDateBlocked()); } @Test @RunAsUser("administrator@fg.cz") public void shouldBlockTerminalAsAdministrator() throws Exception { Terminal terminal = terminalManager.getTerminalById(100); terminalManager.blockTerminal(terminal); } @Test(expected = AccessDeniedException.class) @RunAsUser("merchant@fg.cz") public void shouldFailToBlockTerminalAsMerchant() throws Exception { Terminal terminal = terminalManager.getTerminalById(100); terminalManager.blockTerminal(terminal); } @Test(expected = AccessDeniedException.class) public void shouldFailToBlockTerminalAsUnauthorized() throws Exception { Terminal terminal = terminalManager.

Skryté pastičky v Tomcatu aneb zpětná kompatibilita se všude nenosí

/** * Removes path parameters from each path segment in the supplied path and truncates sequences of multiple '/' * characters to a single '/'. * * @param path either the {@code servletPath} and {@code pathInfo} from the original request * * @return the supplied value, with path parameters removed and sequences of multiple '/' characters truncated, * or null if the supplied path was null. */ private String strip(String path) { if (path == null) { return null; } int scIndex = path.

Combining custom annotations for securing methods with Spring Security

@PreAuthorize("principal.userObject.administrator") public void approveOrganization(Organization organization) { //... content ... } @PreAuthorize("principal.userObject.isOwnerOf(#organization.id) or principal.userObject.administrator") public void updateOrganization(Organization organization) { //... content ... } @PreAuthorize("(branch.isPartOf(organization) and principal.userObject.isManagerOf(#branch.id)) or principal.userObject.isOwnerOf(#organization.id) or principal.userObject.administrator") public void updateOrganizationBranch(Organization organization, Branch branch) { //... content ... } //and more ... example was shortened principal.userObject.administrator // means administrator with super rights is logged in principal.userObject.isOwnerOf(#organization.id) // means user that is owner of particular organization //(has super rights related to his organization) is logged in branch.