I am using CQ5.6 and making a servlet call from a service. In my error log I get "java.io.IOException: Server returned HTTP response code: 401 for URL: http://localhost:4502/content/sports/jcr:content/parSports/sportsscores.scores" from a log statement.
How do I resolve this issue? (I am not doing anything with credentials)
Here is my service:
mport org.apache.felix.scr.annotations.Activate
import org.apache.felix.scr.annotations.Component
import org.apache.felix.scr.annotations.Properties
import org.apache.felix.scr.annotations.Property
import org.apache.felix.scr.annotations.Service
import org.osgi.service.component.ComponentContext
import org.apache.sling.commons.osgi.PropertiesUtil
@groovy.util.logging.Slf4j
@Component(label = "SportsScoresInit Service", description =
"Call the servlet that gets the sports scores", immediate = true, metatype =
true)
@Service(ScoresInterface.class)
@Properties([
@Property(label = "Dummy", name = "dummy", value = "Default dummy")
])
public class SportsScoresInitial implements ScoresInterface {
public String scoresFromServlet = "Default"
public String getScoresFromServlet() {
setScoresFromServlet()
return scoresFromServlet
}
public void setScoresFromServlet() {
//date = request.getParameter("date")
//log.debug("date: {}",date)
log.debug("In service to call servlet")
String urlString = "http://localhost:4502/content/sports/jcr:content/parSports/sportsscores.scores"
log.debug("urlString: " + urlString)
URL url = null
HttpURLConnection connection = null
int responseCode = -9
String result = ""
log.debug("Before call to Sports Scores servlet")
long startTime = System.currentTimeMillis()
try {
url = new URL(urlString)
log.debug("url: " + url)
connection = (HttpURLConnection) url.openConnection()
log.debug("Connection: " + connection)
connection.setRequestMethod("GET")
responseCode = connection.getResponseCode()
log.debug("After calling Sports Scores servlet")
BufferedReader reader
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))
log.debug("reader: " + reader)
result = reader.readLine()
long stopTime = System.currentTimeMillis()
long elapsedTime = stopTime - startTime
log.debug("Elapsed Time is... " + elapsedTime)
log.debug("result: " + result)
PrintWriter writer = response.getWriter()
response.setContentType("application/json")
response.setCharacterEncoding("UTF-8")
//writer.write(result)
} catch (MalformedURLException e) {
log.error("MalformedURL")
e.printStackTrace()
log.debug("Cause: " + e.getCause())
} catch (IOException e) {
log.error("IOException")
e.printStackTrace()
log.debug("Cause: " + e.getCause())
}
scoresFromServlet = result
}
}
// Pulls data from OSGi
@Activate
protected void activate(ComponentContext ctx) {
// Grab property values and store to class variables
//message = PropertiesUtil.toString(ctx.getProperties().get("message"), "Welcome to this service too")
}
and this is my servlet:
import org.apache.sling.commons.osgi.PropertiesUtil
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
import org.apache.sling.api.servlets.SlingSafeMethodsServlet
import org.apache.sling.api.SlingHttpServletRequest
import org.apache.sling.api.SlingHttpServletResponse
import javax.servlet.ServletException
import org.apache.felix.scr.annotations.Activate
import org.apache.felix.scr.annotations.Properties
import org.apache.felix.scr.annotations.Property
import org.apache.felix.scr.annotations.sling.SlingServlet
import org.osgi.service.component.ComponentContext
import groovy.transform.CompileStatic;
@CompileStatic
@groovy.util.logging.Slf4j
@SlingServlet(
name="sportsScoresServlet",
resourceTypes="icidigital/components/content/sportsScores",
extensions="scores", // put this in the ajax call in the javascript
methods="GET",
metatype=true)
@Properties([
@Property(name="SportsScoresServlet", description="Get JSON String sports scores", value="sports scores")
])
/**
* Handles requests for getting weather information from OpenWeatherMap.org. returns the information as a JSon string.
*/
public class SportsScores extends SlingSafeMethodsServlet {
@Property(label = "The api key", value = 'b0fc12635bbf445aa1a9013c5766fdbf', description = "This is the API Key used to access the Sports Scores API") // register the api key in the OSGi console
private static final String SPORTS_SCORES_API_KEY = "apikey"
private String apikey = ""
private String apikeyTest = ""
private String date = ""
@Override
public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
//System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, 'TRACE');
//Properties p = new Properties(System.getProperties());
//System.setProperty(Dorg.slf4j.simpleLogger.defaultLogLevel, 'TRACE');
log.debug('doGet in SportsScores')
writeScores(request, response)
}
/**
* Gets current weather information from OpenWeatherMap.org API
* @param request
* @param response
* @throws IOException
*/
public void writeScores(SlingHttpServletRequest request, SlingHttpServletResponse response) {
date = request.getParameter("date")
log.debug("date: {}",date)
log.debug("scores api key: {}", apikey)
String urlString = "http://api.nfldata.apiphany.com/mlb/v2/JSON/BoxScores/${date}?subscription-key=${apikey}"
log.debug("urlString: " + urlString)
URL url = null
HttpURLConnection connection = null
int responseCode = -9
String result = ""
log.debug("Before call to FantasyData")
long startTime = System.currentTimeMillis()
try {
url = new URL(urlString)
log.debug("url: " + url)
connection = (HttpURLConnection) url.openConnection()
log.debug("Connection: " + connection)
connection.setRequestMethod("GET")
responseCode = connection.getResponseCode()
log.debug("After calling FantasyData")
BufferedReader reader
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))
log.debug("reader: " + reader)
result = reader.readLine()
//jsonSlurp(result)
long stopTime = System.currentTimeMillis()
long elapsedTime = stopTime - startTime
log.debug("Elapsed Time is... " + elapsedTime)
log.debug("result: " + result)
PrintWriter writer = response.getWriter()
response.setContentType("application/json")
response.setCharacterEncoding("UTF-8")
writer.write(result)
} catch (MalformedURLException e) {
log.error("MalformedURL")
e.printStackTrace()
} catch (IOException e) {
log.error("IOException")
e.printStackTrace()
log.debug("Cause: " + e.getCause())
}
}
@Activate
protected void activate(ComponentContext ctx)
{
Dictionary dict = ctx.getProperties()
apikey = PropertiesUtil.toString(dict.get(SPORTS_SCORES_API_KEY),'');
//apikey = PropertiesUtil.toString(context.getProperties().get("apikey"), "b0fc12635bbf445aa1a9013c5766fdbf") // Get the api key from the OSGi console
log.debug("sports scores servlet activated")
}
}
I don't think what you are trying to do make much sense. Why are you doing an Http connection to the instance itself? You are trying to access an authoring instance, which requires permissions to access it.
It seems you are doing things backwards. You should have a service where you access that third party service, and then use it in your servlet. That way you don't need to use an http connection to the same instance.
Having said that, if you still want to process a request through CQ5 from itself, you can use the SlingRequestProcessor to internally process a request without need to open an actual connection