We are trying to connect to our instance of the CalendarStore but we don't understand the exception, that we get back when executing the code.
The Error we're having:
org.codehaus.groovy.runtime.InvokerInvocationException: net.fortuna.ical4j.connector.ObjectStoreException: net.fortuna.ical4j.connector.FailedOperationException: Principals not found
We also know that the error occurs in line 62. Please note that I have edited the strings in the variables to not expose them to the public.
import com.github.caldav4j.CalDAVCollection;
import com.github.caldav4j.CalDAVConstants;
import com.github.caldav4j.exceptions.CalDAV4JException;
import com.github.caldav4j.methods.CalDAV4JMethodFactory;
import com.github.caldav4j.methods.HttpGetMethod;
import com.github.caldav4j.model.request.CalendarQuery;
import com.github.caldav4j.util.GenerateQuery;
import net.fortuna.ical4j.connector.ObjectStoreException;
import net.fortuna.ical4j.connector.dav.CalDavCalendarCollection;
import net.fortuna.ical4j.connector.dav.CalDavCalendarStore;
import net.fortuna.ical4j.connector.dav.PathResolver;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.DefaultRoutePlanner;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.protocol.HttpContext;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.Date;
import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.connector.CalendarStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
String USER = "User";
String PASS = "dont matter";
g_log.info("Start");
String uri = "our uri";
String prodId = "hm";
URL url = new URL("Our url");
PathResolver pathResolver = PathResolver.CHANDLER;
CalendarStore<CalDavCalendarCollection> calendarStore = new CalDavCalendarStore(prodId, url, pathResolver);
boolean testCon = calendarStore.connect(USER.toString(), PASS.toCharArray());
g_log.info("testCon: "+ testCon);
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from rest_framework import serializers
from rest_framework import parsers
from rest_framework.parsers import JSONParser
from .models import Article
from .serializer import Articleserializer
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
# Create your views here.
def artical_list(request):
if request.method=='GET':
article= Article.objects.all()
serializer=Articleserializer(article,many=True)
return JsonResponse(serializer.data,safe=False)
elif request.method=='POST':
data=JSONParser.parse(request)
serializer=Articleserializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data,status=201)
return JsonResponse(serializer.errors, status=400)
this is my serializer class
from django.db.models import fields
from rest_framework import serializers
from .models import Article
class Articleserializer(serializers.ModelSerializer):
class Meta:
model=Article
fields= ['id','title','author']
this is my model class
from django.db import models
# Create your models here.
class Article(models.Model):
title=models.CharField(max_length=50)
author=models.CharField(max_length=100)
email=models.EmailField(max_length=100)
date=models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
when I post the data using postman giving this error please help me django rest freamwork is
The JSONParser should be instantiated. The parse method is a normal method, not a classmethod. So you need a instance for it to work:
JSONParser().parse(request) # Instead of JSONParser.parse(request)
I want to upload image with the name (which is given by user) at Django server through rest API,but i am not be able to find out the solution for this.Please tell me how to upload image with given name.
here is my code(mainly):
IN API TASK ->URLS:
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework import routers
from django.conf import settings
from myapi import views
from django.conf.urls.static import static
#Define API Routes
router = routers.DefaultRouter()
router.register(r'myimage', views.myimageViewSet) #we have only on viewset
urlpatterns = [
url(r'^',include(router.urls)),
url(r'^admin/',admin.site.urls),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
IN My API
1. MODEL
from django.db import models
# Create your models here.
class myimage(models.Model):
my_name=models.CharField(max_length=50)
my_image=models.ImageField(upload_to='Images/',default='Images/None/No-img.jpg')
def __str__(self):
return self.my_name
2.SERIALIZERS
from rest_framework import serializers
from .models import myimage
class myimageserializer(serializers.ModelSerializer):
class Meta:
model =myimage
fields=('id','my_name','my_image')
3. VIEWS
from django.shortcuts import render
from .models import myimage
from rest_framework import viewsets
from .serializers import myimageserializer
from rest_framework import filters
import django_filters.rest_framework
class myimageViewSet(viewsets.ModelViewSet):
queryset = myimage.objects.all() #We use Filters for Ordering so remove order_by part
serializer_class = myimageserializer
filter_backends = (django_filters.rest_framework.DjangoFilterBackend,filters.OrderingFilter,)
ordering = ('id','my_name',)
4.ADMIN
from django.contrib import admin
from .models import myimage
admin.site.register(myimage)
You need to use FileParser to be able to get your image details in the request data object. I recommend you to follow the example in DRF's FileParser Example
I changed my code as mentioned below and now its working for me if you have any better solution please suggest here #happycoding
1. views.py
from django.shortcuts import render
from .models import myimage
from rest_framework import views
from .serializers import myimageserializer
import django_filters.rest_framework
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class myimageView(APIView):
def get(self, request):
myimagelocal= myimage.objects.all()
serializer = myimageserializer(myimagelocal, many=True)
return Response(serializer.data)
def post(self, request):
myname=request.data['my_image'].name
myformat=""
for c in reversed(myname):
myformat+=c
if c=='.' :
break
myformat=myformat[: : -1]
request.FILES['my_image'].name=request.data['my_name']+myformat
serializer = myimageserializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
IN API_TASK->URLS:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls,name='admin'),
path('',include('myapi.urls'))
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
IN API_Task->myapi->url
from django.urls import path
from .views import myimagedetailsView, myimageView
urlpatterns = [
path('myimage/', myimageView.as_view(),name='myimageView'),
]
Rest files unchanged
I am having a server.py file which is written in Falcon. Which looks like this.
try:
import falcon, logging
from os.path import dirname, realpath, join
from wsgiref import simple_server
from .config.config import server_config
from .middlewares.SQLAlchemySessionManager import SQLAlchemySessionManager
from .middlewares.GlobalInternalServerErrorManager import InternalServerErrorManager
from .lib.dbConnector import Session
from .routes import router
except ImportError as err:
falcon = None
raise err
serv_conf = server_config()
salescoachbot = falcon.API(middleware= [
SQLAlchemySessionManager(Session),
InternalServerErrorManager()
])
But when I am trying to import "salescoachbot" to other folder and files
like:
from ..server import salescoachbot
This gives me an error saying that the
from ..server import salescoachbot
ImportError: cannot import name 'salescoachbot'
The server.py is in the root of the project and has an init.py as well as the file which is trying to import the name.
What am I doing wrong here?
import org.apache.spark.SparkConf
import org.apache.spark.storage.StorageLevel
import org.apache.spark.streaming.Milliseconds
import org.apache.spark.streaming.StreamingContext
import org.apache.spark.streaming.dstream.DStream.toPairDStreamFunctions
import com.amazonaws.auth.AWSCredentials
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain
import com.amazonaws.auth.SystemPropertiesCredentialsProvider
import com.amazonaws.services.kinesis.AmazonKinesisClient
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.InitialPositionInStream
import org.apache.spark.streaming.kinesis.KinesisInputDStream
import org.apache.spark.streaming.kinesis.KinesisInitialPositions.Latest
import org.apache.spark.streaming.kinesis.KinesisInitialPositions.TrimHorizon
import java.util.Date
val tStream = KinesisInputDStream.builder
.streamingContext(ssc)
.streamName(streamName)
.endpointUrl(endpointUrl)
.regionName(regionName)
.initialPosition(new TrimHorizon())
.checkpointAppName(appName)
.checkpointInterval(kinesisCheckpointInterval)
.storageLevel(StorageLevel.MEMORY_AND_DISK_2)
.build()
tStream.foreachRDD(rdd => if (rdd.count() > 0) rdd.saveAsTextFile("/user/hdfs/test/") else println("No record to read"))
Here, even though I see data coming into the stream, my above spark job isn't getting any records. I am sure that I am connecting to right stream with all credentials.
Please help me out.