Skip to content

Content of file DefaultEmbeddedServer.java.html

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="../../jacoco-resources/report.css" type="text/css"/><link rel="shortcut icon" href="../../jacoco-resources/report.gif" type="image/gif"/><title>DefaultEmbeddedServer.java</title><link rel="stylesheet" href="../../jacoco-resources/prettify.css" type="text/css"/><script type="text/javascript" src="../../jacoco-resources/prettify.js"></script></head><body onload="window['PR_TAB_WIDTH']=4;prettyPrint()"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="../../jacoco-sessions.html" class="el_session">Sessions</a></span><a href="../../index.html" class="el_report">Zephyr - UI Content Editor</a> &gt; <a href="../index.html" class="el_bundle">it-tidalwave-northernwind-rca-embeddedserver</a> &gt; <a href="index.source.html" class="el_package">it.tidalwave.northernwind.rca.embeddedserver.impl</a> &gt; <span class="el_source">DefaultEmbeddedServer.java</span></div><h1>DefaultEmbeddedServer.java</h1><pre class="source lang-java linenums"><span class="fc" id="L1">/*</span>
 * #%L
 * *********************************************************************************************************************
 *
 * NorthernWind - lightweight CMS
 * http://northernwind.tidalwave.it - git clone git@bitbucket.org:tidalwave/northernwind-rca-src.git
 * %%
 * Copyright (C) 2013 - 2021 Tidalwave s.a.s. (http://tidalwave.it)
 * %%
 * *********************************************************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations under the License.
 *
 * *********************************************************************************************************************
 *
 *
 * *********************************************************************************************************************
 * #L%
 */
package it.tidalwave.northernwind.rca.embeddedserver.impl;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.Map;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.FileNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.common.io.ByteStreams;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.eclipse.jetty.server.Server;
import it.tidalwave.messagebus.annotation.ListensTo;
import it.tidalwave.messagebus.annotation.SimpleMessageSubscriber;
import it.tidalwave.northernwind.core.impl.filter.LibraryLinkMacroFilter;
import it.tidalwave.northernwind.core.impl.filter.MediaLinkMacroFilter;
import it.tidalwave.northernwind.core.model.MimeTypeResolver;
import it.tidalwave.northernwind.core.model.ResourceFile;
import it.tidalwave.northernwind.core.model.ResourceFileSystem;
import it.tidalwave.northernwind.rca.embeddedserver.EmbeddedServer;
import it.tidalwave.northernwind.rca.ui.event.OpenSiteEvent;
import lombok.Cleanup;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import static java.util.stream.Collectors.joining;

/***********************************************************************************************************************
 *
 * @author  Fabrizio Giudici
 *
 **********************************************************************************************************************/
<span class="pc bpc" id="L65" title="1 of 2 branches missed.">@SimpleMessageSubscriber @RequiredArgsConstructor @Slf4j</span>
public class DefaultEmbeddedServer implements EmbeddedServer
  {
    @Nonnull
    private final MimeTypeResolver mimeTypeResolver;

<span class="pc" id="L71">    @Getter @Setter</span>
    private int port = 12345;

    @CheckForNull
    /* visible for testing */ Server server;

<span class="fc" id="L77">    private final Map&lt;String, Document&gt; documentMapByUrl = new HashMap&lt;&gt;();</span>

    @CheckForNull
    private ResourceFileSystem fileSystem;

    /*******************************************************************************************************************
     *
     *
     *
     ******************************************************************************************************************/
<span class="fc" id="L87">    private final ServletAdapter servlet = new ServletAdapter()</span>
<span class="fc" id="L88">      {</span>
        private static final long serialVersionUID = -2887261966375531858L;

<span class="fc" id="L91">        private final MediaLinkMacroFilter mediaLinkMacroFilter = new MediaLinkMacroFilter();</span>
<span class="fc" id="L92">        private final LibraryLinkMacroFilter libraryLinkMacroFilter = new LibraryLinkMacroFilter();</span>

        @Override
        protected void doGet (final @Nonnull HttpServletRequest request,
                              final @Nonnull HttpServletResponse response)
          throws ServletException, IOException
          {
<span class="fc" id="L99">            String uri = request.getRequestURI();</span>
<span class="fc" id="L100">            log.debug(&quot;doGet({})&quot;, uri);</span>
            // FIXME: use a pipeline for handling those requests - eventually integrate support already in Site

<span class="fc" id="L103">            uri = mediaLinkMacroFilter.filter(uri, &quot;&quot;);</span>
<span class="fc" id="L104">            uri = libraryLinkMacroFilter.filter(uri, &quot;&quot;);</span>
<span class="fc" id="L105">            uri = uri.replace(&quot;//&quot;, &quot;/&quot;); // Aloha puts a leading / before the macro</span>
<span class="fc" id="L106">            log.debug(&quot;&gt;&gt;&gt; filtered {}&quot;, uri);</span>

<span class="pc bpc" id="L108" title="1 of 2 branches missed.">            if (uri.startsWith(&quot;/nwa/&quot;)) // FIXME - and use ResourcePath</span>
- and use ResourcePath
{ <span class="nc" id="L110"> serveEditorResources(uri, response);</span> } <span class="pc bpc" id="L113" title="2 of 4 branches missed."> else if (uri.startsWith(&quot;/library/&quot;) || uri.startsWith(&quot;/media/&quot;)) // FIXME - and use ResourcePath</span> { <span class="nc" id="L115"> serveContentResources(uri, response);</span> } else { <span class="fc" id="L120"> serveRegisteredResources(uri, response);</span> } <span class="fc" id="L122"> }</span> @Override protected void doPut (final @Nonnull HttpServletRequest request, final @Nonnull HttpServletResponse response) throws ServletException, IOException { <span class="nc" id="L129"> final String uri = request.getRequestURI();</span> <span class="nc" id="L130"> log.debug(&quot;doPut({})&quot;, uri);</span> <span class="nc" id="L131"> updateRegisteredResource(request, response);</span> <span class="nc" id="L132"> }</span> }; /******************************************************************************************************************* * * * * ******************************************************************************************************************/ /* visible for testing */ void onOpenSite (final @ListensTo @Nonnull OpenSiteEvent event) { <span class="nc" id="L143"> log.debug(&quot;onOpenSite({})&quot;, event);</span> <span class="nc" id="L144"> fileSystem = event.getFileSystem();</span> <span class="nc" id="L145"> }</span> /******************************************************************************************************************* * * * * ******************************************************************************************************************/ @PostConstruct public void start() { try { <span class="fc" id="L158"> log.info(&quot;Starting webserver on port {}...&quot;, port);</span> <span class="fc" id="L159"> server = new Server(port);</span> <span class="fc" id="L160"> server.setHandler(servlet.asHandler());</span> <span class="fc" id="L161"> server.start();</span> <span class="fc" id="L162"> log.info(&quot;&gt;&gt;&gt;&gt; started&quot;);</span> } <span class="nc" id="L164"> catch (Exception e)</span> { <span class="nc" id="L166"> log.error(&quot;&quot;, e);</span> <span class="fc" id="L167"> }</span> <span class="fc" id="L168"> }</span> /******************************************************************************************************************* * * * * ******************************************************************************************************************/ @PreDestroy public void stop() { try { <span class="pc bpc" id="L181" title="3 of 6 branches missed."> if ((server != null) &amp;&amp; !server.isStopping() &amp;&amp; !server.isStopped())</span> { <span class="fc" id="L183"> log.info(&quot;Stopping webserver...&quot;);</span> <span class="fc" id="L184"> server.stop();</span> <span class="fc" id="L185"> log.info(&quot;&gt;&gt;&gt;&gt; stopped&quot;);</span> } } <span class="nc" id="L188"> catch (Exception e)</span> { <span class="nc" id="L190"> log.error(&quot;&quot;, e);</span> <span class="fc" id="L191"> }</span> <span class="fc" id="L192"> }</span> /******************************************************************************************************************* * * * * ******************************************************************************************************************/ @Override @Nonnull public String putDocument (final @Nonnull String path, final @Nonnull Document document) { <span class="fc" id="L203"> documentMapByUrl.put(path, document);</span> <span class="fc" id="L204"> return String.format(&quot;http://localhost:%d%s&quot;, port, path);</span> } /******************************************************************************************************************* * * * ******************************************************************************************************************/ private void serveEditorResources (final @Nonnull String uri, final @Nonnull HttpServletResponse response) throws IOException { try { <span class="nc" id="L218"> final byte[] resource = loadResource(uri);</span> <span class="nc" id="L219"> response.setCharacterEncoding(&quot;&quot;);</span> <span class="nc" id="L220"> response.setContentType(mimeTypeResolver.getMimeType(uri));</span> <span class="nc" id="L221"> response.setStatus(HttpServletResponse.SC_OK);</span> <span class="nc" id="L222"> response.getOutputStream().write(resource);</span> } <span class="nc" id="L224"> catch (FileNotFoundException e)</span> { <span class="nc" id="L226"> log.warn(&quot;2 - Not found: {}&quot;, uri);</span> <span class="nc" id="L227"> response.setStatus(HttpServletResponse.SC_NOT_FOUND);</span> <span class="nc" id="L228"> }</span> <span class="nc" id="L229"> }</span> /******************************************************************************************************************* * * * ******************************************************************************************************************/ private void serveContentResources (final @Nonnull String uri, final @Nonnull HttpServletResponse response) throws IOException { <span class="nc" id="L240"> log.debug(&quot;serveLibraryResources({})&quot;, uri);</span> // don't bother when there's no opened Site <span class="nc bnc" id="L243" title="All 2 branches missed."> if (fileSystem == null)</span> { <span class="nc" id="L245"> response.setStatus(HttpServletResponse.SC_OK);</span> } else { <span class="nc" id="L249"> final ResourceFile file = fileSystem.findFileByPath(&quot;/content&quot; + uri); // FIXME</span> <span class="nc bnc" id="L251" title="All 2 branches missed."> if (file == null)</span> { <span class="nc" id="L253"> log.warn(&quot;5 - Not found: {}&quot;, &quot;/content&quot; + uri);</span> <span class="nc" id="L254"> response.setStatus(HttpServletResponse.SC_NOT_FOUND);</span> <span class="nc" id="L255"> return;</span> } <span class="nc" id="L258"> final String mimeType = file.getMimeType();</span> <span class="nc" id="L259"> response.setContentType(mimeType);</span> <span class="nc" id="L260"> response.setStatus(HttpServletResponse.SC_OK);</span> <span class="nc bnc" id="L262" title="All 2 branches missed."> if (mimeType.startsWith(&quot;image&quot;))</span> { <span class="nc" id="L264"> response.getOutputStream().write(file.asBytes());</span> } else { <span class="nc" id="L268"> response.setCharacterEncoding(&quot;UTF-8&quot;);</span> <span class="nc" id="L269"> response.getWriter().write(file.asText(&quot;UTF-8&quot;));</span> } } <span class="nc" id="L272"> }</span> /******************************************************************************************************************* * * * ******************************************************************************************************************/ private void serveRegisteredResources (final @Nonnull String uri, final @Nonnull HttpServletResponse response) throws IOException { <span class="fc" id="L283"> final Document document = documentMapByUrl.get(uri);</span> <span class="fc bfc" id="L285" title="All 2 branches covered."> if (document == null)</span> { <span class="fc" id="L287"> log.warn(&quot;1 - Not found: {}&quot;, uri);</span> <span class="fc" id="L288"> response.setStatus(HttpServletResponse.SC_NOT_FOUND);</span> } else { <span class="fc" id="L292"> response.setCharacterEncoding(&quot;UTF-8&quot;);</span> <span class="fc" id="L293"> response.setContentType(document.getMimeType());</span> <span class="fc" id="L294"> response.setStatus(HttpServletResponse.SC_OK);</span> <span class="fc" id="L295"> response.getWriter().write(document.getContent());</span> } <span class="fc" id="L297"> }</span> /******************************************************************************************************************* * * * ******************************************************************************************************************/ private void updateRegisteredResource (final @Nonnull HttpServletRequest request, final @Nonnull HttpServletResponse response) throws IOException { <span class="nc" id="L308"> final String uri = request.getRequestURI();</span> <span class="nc" id="L309"> final String body = request.getReader().lines().collect(joining(&quot;\n&quot;));</span> <span class="nc" id="L311"> final Document document = documentMapByUrl.get(uri);</span> <span class="nc bnc" id="L313" title="All 2 branches missed."> if (document == null)</span> { <span class="nc" id="L315"> log.warn(&quot;3 - Not found: {}&quot;, uri);</span> <span class="nc" id="L316"> response.setStatus(HttpServletResponse.SC_NOT_FOUND);</span> } else { <span class="nc" id="L320"> document.update(body);</span> <span class="nc" id="L321"> response.setStatus(HttpServletResponse.SC_OK);</span> } <span class="nc" id="L323"> }</span> /******************************************************************************************************************* * * * ******************************************************************************************************************/ @Nonnull /* visible for testing */ byte[] loadResource (final @Nonnull String path) throws IOException { <span class="nc" id="L334"> final ClassPathResource resource = new ClassPathResource(path);</span> <span class="nc bnc" id="L335" title="All 2 branches missed."> final @Cleanup DataInputStream is = new DataInputStream(resource.getInputStream());</span> <span class="nc" id="L336"> return ByteStreams.toByteArray(is);</span> } } </pre><div class="footer"><span class="right">Created with <a href="http://www.jacoco.org/jacoco">JaCoCo</a> 0.8.6.202009150832</span></div></body></html>